|
| 1 | +/* |
| 2 | +Copyright 2020 The Kubernetes Authors All rights reserved. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package audit |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "os" |
| 22 | + |
| 23 | + "k8s.io/minikube/pkg/minikube/localpath" |
| 24 | + "k8s.io/minikube/pkg/minikube/out/register" |
| 25 | +) |
| 26 | + |
| 27 | +var ( |
| 28 | + file *os.File |
| 29 | + logPath string |
| 30 | +) |
| 31 | + |
| 32 | +// setLogFile sets the logPath and creates the log file if it doesn't exist. |
| 33 | +func setLogFile() error { |
| 34 | + logPath = localpath.AuditLog() |
| 35 | + if _, err := os.Stat(logPath); os.IsNotExist(err) { |
| 36 | + return createLogFile() |
| 37 | + } |
| 38 | + f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, os.ModeAppend) |
| 39 | + if err != nil { |
| 40 | + return fmt.Errorf("unable to open %s: %v", logPath, err) |
| 41 | + } |
| 42 | + file = f |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +// createLogFile creates the file used for logging audits. |
| 47 | +func createLogFile() error { |
| 48 | + f, err := os.Create(logPath) |
| 49 | + if err != nil { |
| 50 | + return fmt.Errorf("unable to create file %s: %v", logPath, err) |
| 51 | + } |
| 52 | + file = f |
| 53 | + return nil |
| 54 | +} |
| 55 | + |
| 56 | +// appendToLog appends the audit entry to the log file. |
| 57 | +func appendToLog(entry *entry) error { |
| 58 | + if file == nil { |
| 59 | + if err := setLogFile(); err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + } |
| 63 | + e := register.CloudEvent(entry, entry.data) |
| 64 | + bs, err := e.MarshalJSON() |
| 65 | + if err != nil { |
| 66 | + return fmt.Errorf("error marshalling event: %v", err) |
| 67 | + } |
| 68 | + if _, err := file.WriteString(string(bs) + "\n"); err != nil { |
| 69 | + return fmt.Errorf("unable to write to %s: %v", logPath, err) |
| 70 | + } |
| 71 | + return nil |
| 72 | +} |
0 commit comments