|
| 1 | +package service |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "log" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +// SwarmServicePolling provides an interface for polling service changes |
| 10 | +type SwarmServicePolling interface { |
| 11 | + Run(eventChan chan<- Event) |
| 12 | +} |
| 13 | + |
| 14 | +// SwarmServicePoller implements `SwarmServicePoller` |
| 15 | +type SwarmServicePoller struct { |
| 16 | + SSClient SwarmServiceInspector |
| 17 | + SSCache SwarmServiceCacher |
| 18 | + PollingInterval int |
| 19 | + MinifyFunc func(SwarmService) SwarmServiceMini |
| 20 | + Log *log.Logger |
| 21 | +} |
| 22 | + |
| 23 | +// NewSwarmServicePoller creates a new `SwarmServicePoller` |
| 24 | +func NewSwarmServicePoller( |
| 25 | + ssClient SwarmServiceInspector, |
| 26 | + ssCache SwarmServiceCacher, |
| 27 | + pollingInterval int, |
| 28 | + minifyFunc func(SwarmService) SwarmServiceMini, |
| 29 | + log *log.Logger, |
| 30 | +) *SwarmServicePoller { |
| 31 | + return &SwarmServicePoller{ |
| 32 | + SSClient: ssClient, |
| 33 | + SSCache: ssCache, |
| 34 | + PollingInterval: pollingInterval, |
| 35 | + MinifyFunc: minifyFunc, |
| 36 | + Log: log, |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +// Run starts poller and places events onto `eventChan` |
| 41 | +func (s SwarmServicePoller) Run( |
| 42 | + eventChan chan<- Event) { |
| 43 | + |
| 44 | + if s.PollingInterval <= 0 { |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + s.Log.Printf("Polling for Service Changes") |
| 49 | + time.Sleep(time.Duration(s.PollingInterval) * time.Second) |
| 50 | + for { |
| 51 | + services, err := s.SSClient.SwarmServiceList(context.Background()) |
| 52 | + if err != nil { |
| 53 | + s.Log.Printf("ERROR (SwarmServicePolling): %v", err) |
| 54 | + } else { |
| 55 | + nowTimeNano := time.Now().UTC().UnixNano() |
| 56 | + keys := s.SSCache.Keys() |
| 57 | + for _, ss := range services { |
| 58 | + delete(keys, ss.ID) |
| 59 | + ssMini := s.MinifyFunc(ss) |
| 60 | + if s.SSCache.IsNewOrUpdated(ssMini) { |
| 61 | + eventChan <- Event{ |
| 62 | + Type: EventTypeCreate, |
| 63 | + ID: ss.ID, |
| 64 | + TimeNano: nowTimeNano, |
| 65 | + UseCache: true, |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + // Remaining keys are removal events |
| 71 | + for k := range keys { |
| 72 | + eventChan <- Event{ |
| 73 | + Type: EventTypeRemove, |
| 74 | + ID: k, |
| 75 | + TimeNano: nowTimeNano, |
| 76 | + UseCache: true, |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + time.Sleep(time.Duration(s.PollingInterval) * time.Second) |
| 81 | + } |
| 82 | +} |
0 commit comments