github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/libpod/events/logfile.go (about) 1 package events 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/containers/storage" 8 "github.com/pkg/errors" 9 ) 10 11 // EventLogFile is the structure for event writing to a logfile. It contains the eventer 12 // options and the event itself. Methods for reading and writing are also defined from it. 13 type EventLogFile struct { 14 options EventerOptions 15 } 16 17 // Writes to the log file 18 func (e EventLogFile) Write(ee Event) error { 19 // We need to lock events file 20 lock, err := storage.GetLockfile(e.options.LogFilePath + ".lock") 21 if err != nil { 22 return err 23 } 24 lock.Lock() 25 defer lock.Unlock() 26 f, err := os.OpenFile(e.options.LogFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0700) 27 if err != nil { 28 return err 29 } 30 defer f.Close() 31 eventJSONString, err := ee.ToJSONString() 32 if err != nil { 33 return err 34 } 35 if _, err := f.WriteString(fmt.Sprintf("%s\n", eventJSONString)); err != nil { 36 return err 37 } 38 return nil 39 40 } 41 42 // Reads from the log file 43 func (e EventLogFile) Read(options ReadOptions) error { 44 defer close(options.EventChannel) 45 eventOptions, err := generateEventOptions(options.Filters, options.Since, options.Until) 46 if err != nil { 47 return errors.Wrapf(err, "unable to generate event options") 48 } 49 t, err := e.getTail(options) 50 if err != nil { 51 return err 52 } 53 for line := range t.Lines { 54 event, err := newEventFromJSONString(line.Text) 55 if err != nil { 56 return err 57 } 58 switch event.Type { 59 case Image, Volume, Pod, System, Container: 60 // no-op 61 default: 62 return errors.Errorf("event type %s is not valid in %s", event.Type.String(), e.options.LogFilePath) 63 } 64 include := true 65 for _, filter := range eventOptions { 66 include = include && filter(event) 67 } 68 if include { 69 options.EventChannel <- event 70 } 71 } 72 return nil 73 } 74 75 // String returns a string representation of the logger 76 func (e EventLogFile) String() string { 77 return LogFile.String() 78 }