github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/libnetwork/networkdb/watch.go (about) 1 package networkdb 2 3 import ( 4 "net" 5 6 "github.com/docker/go-events" 7 ) 8 9 type opType uint8 10 11 const ( 12 opCreate opType = 1 + iota 13 opUpdate 14 opDelete 15 ) 16 17 type event struct { 18 Table string 19 NetworkID string 20 Key string 21 Value []byte 22 } 23 24 // NodeTable represents table event for node join and leave 25 const NodeTable = "NodeTable" 26 27 // NodeAddr represents the value carried for node event in NodeTable 28 type NodeAddr struct { 29 Addr net.IP 30 } 31 32 // CreateEvent generates a table entry create event to the watchers 33 type CreateEvent event 34 35 // UpdateEvent generates a table entry update event to the watchers 36 type UpdateEvent event 37 38 // DeleteEvent generates a table entry delete event to the watchers 39 type DeleteEvent event 40 41 // Watch creates a watcher with filters for a particular table or 42 // network or any combination of the tuple. If any of the 43 // filter is an empty string it acts as a wildcard for that 44 // field. Watch returns a channel of events, where the events will be 45 // sent. 46 func (nDB *NetworkDB) Watch(tname, nid string) (*events.Channel, func()) { 47 var matcher events.Matcher 48 49 if tname != "" || nid != "" { 50 matcher = events.MatcherFunc(func(ev events.Event) bool { 51 var evt event 52 switch ev := ev.(type) { 53 case CreateEvent: 54 evt = event(ev) 55 case UpdateEvent: 56 evt = event(ev) 57 case DeleteEvent: 58 evt = event(ev) 59 } 60 61 if tname != "" && evt.Table != tname { 62 return false 63 } 64 65 if nid != "" && evt.NetworkID != nid { 66 return false 67 } 68 69 return true 70 }) 71 } 72 73 ch := events.NewChannel(0) 74 sink := events.Sink(events.NewQueue(ch)) 75 76 if matcher != nil { 77 sink = events.NewFilter(sink, matcher) 78 } 79 80 nDB.broadcaster.Add(sink) 81 return ch, func() { 82 nDB.broadcaster.Remove(sink) 83 ch.Close() 84 sink.Close() 85 } 86 } 87 88 func makeEvent(op opType, tname, nid, key string, value []byte) events.Event { 89 ev := event{ 90 Table: tname, 91 NetworkID: nid, 92 Key: key, 93 Value: value, 94 } 95 96 switch op { 97 case opCreate: 98 return CreateEvent(ev) 99 case opUpdate: 100 return UpdateEvent(ev) 101 case opDelete: 102 return DeleteEvent(ev) 103 } 104 105 return nil 106 }