github.com/containers/libpod@v1.9.4-0.20220419124438-4284fd425507/libpod/events/filters.go (about) 1 package events 2 3 import ( 4 "strings" 5 "time" 6 7 "github.com/containers/libpod/pkg/util" 8 "github.com/pkg/errors" 9 ) 10 11 func generateEventFilter(filter, filterValue string) (func(e *Event) bool, error) { 12 switch strings.ToUpper(filter) { 13 case "CONTAINER": 14 return func(e *Event) bool { 15 if e.Type != Container { 16 return false 17 } 18 if e.Name == filterValue { 19 return true 20 } 21 return strings.HasPrefix(e.ID, filterValue) 22 }, nil 23 case "EVENT", "STATUS": 24 return func(e *Event) bool { 25 return string(e.Status) == filterValue 26 }, nil 27 case "IMAGE": 28 return func(e *Event) bool { 29 if e.Type != Image { 30 return false 31 } 32 if e.Name == filterValue { 33 return true 34 } 35 return strings.HasPrefix(e.ID, filterValue) 36 }, nil 37 case "POD": 38 return func(e *Event) bool { 39 if e.Type != Pod { 40 return false 41 } 42 if e.Name == filterValue { 43 return true 44 } 45 return strings.HasPrefix(e.ID, filterValue) 46 }, nil 47 case "VOLUME": 48 return func(e *Event) bool { 49 if e.Type != Volume { 50 return false 51 } 52 return strings.HasPrefix(e.ID, filterValue) 53 }, nil 54 case "TYPE": 55 return func(e *Event) bool { 56 return string(e.Type) == filterValue 57 }, nil 58 } 59 return nil, errors.Errorf("%s is an invalid filter", filter) 60 } 61 62 func generateEventSinceOption(timeSince time.Time) func(e *Event) bool { 63 return func(e *Event) bool { 64 return e.Time.After(timeSince) 65 } 66 } 67 68 func generateEventUntilOption(timeUntil time.Time) func(e *Event) bool { 69 return func(e *Event) bool { 70 return e.Time.Before(timeUntil) 71 72 } 73 } 74 75 func parseFilter(filter string) (string, string, error) { 76 filterSplit := strings.Split(filter, "=") 77 if len(filterSplit) != 2 { 78 return "", "", errors.Errorf("%s is an invalid filter", filter) 79 } 80 return filterSplit[0], filterSplit[1], nil 81 } 82 83 func generateEventOptions(filters []string, since, until string) ([]EventFilter, error) { 84 var options []EventFilter 85 for _, filter := range filters { 86 key, val, err := parseFilter(filter) 87 if err != nil { 88 return nil, err 89 } 90 funcFilter, err := generateEventFilter(key, val) 91 if err != nil { 92 return nil, err 93 } 94 options = append(options, funcFilter) 95 } 96 97 if len(since) > 0 { 98 timeSince, err := util.ParseInputTime(since) 99 if err != nil { 100 return nil, errors.Wrapf(err, "unable to convert since time of %s", since) 101 } 102 options = append(options, generateEventSinceOption(timeSince)) 103 } 104 105 if len(until) > 0 { 106 timeUntil, err := util.ParseInputTime(until) 107 if err != nil { 108 return nil, errors.Wrapf(err, "unable to convert until time of %s", until) 109 } 110 options = append(options, generateEventUntilOption(timeUntil)) 111 } 112 return options, nil 113 }