utils.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package audit
  14. import (
  15. "io/ioutil"
  16. "os"
  17. "path/filepath"
  18. "github.com/pkg/errors"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/runtime"
  21. "k8s.io/apimachinery/pkg/runtime/serializer"
  22. "k8s.io/apiserver/pkg/apis/audit/install"
  23. auditv1 "k8s.io/apiserver/pkg/apis/audit/v1"
  24. "k8s.io/kubernetes/cmd/kubeadm/app/util"
  25. )
  26. // CreateDefaultAuditLogPolicy writes the default audit log policy to disk.
  27. func CreateDefaultAuditLogPolicy(policyFile string) error {
  28. policy := auditv1.Policy{
  29. TypeMeta: metav1.TypeMeta{
  30. APIVersion: auditv1.SchemeGroupVersion.String(),
  31. Kind: "Policy",
  32. },
  33. Rules: []auditv1.PolicyRule{
  34. {
  35. Level: auditv1.LevelMetadata,
  36. },
  37. },
  38. }
  39. return writePolicyToDisk(policyFile, &policy)
  40. }
  41. func writePolicyToDisk(policyFile string, policy *auditv1.Policy) error {
  42. // creates target folder if not already exists
  43. if err := os.MkdirAll(filepath.Dir(policyFile), 0700); err != nil {
  44. return errors.Wrapf(err, "failed to create directory %q: ", filepath.Dir(policyFile))
  45. }
  46. scheme := runtime.NewScheme()
  47. // Registers the API group with the scheme and adds types to a scheme
  48. install.Install(scheme)
  49. codecs := serializer.NewCodecFactory(scheme)
  50. // writes the policy to disk
  51. serialized, err := util.MarshalToYamlForCodecs(policy, auditv1.SchemeGroupVersion, codecs)
  52. if err != nil {
  53. return errors.Wrap(err, "failed to marshal audit policy to YAML")
  54. }
  55. if err := ioutil.WriteFile(policyFile, serialized, 0600); err != nil {
  56. return errors.Wrapf(err, "failed to write audit policy to %v: ", policyFile)
  57. }
  58. return nil
  59. }