app_manager.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package overwatch
  2. // ServiceCallback is a service notify it's runloop finished.
  3. // the first parameter is the service type
  4. // the second parameter is the service name
  5. // the third parameter is an optional error if the service failed
  6. type ServiceCallback func(string, string, error)
  7. // AppManager is the default implementation of overwatch service management
  8. type AppManager struct {
  9. services map[string]Service
  10. callback ServiceCallback
  11. }
  12. // NewAppManager creates a new overwatch manager
  13. func NewAppManager(callback ServiceCallback) Manager {
  14. return &AppManager{services: make(map[string]Service), callback: callback}
  15. }
  16. // Add takes in a new service to manage.
  17. // It stops the service if it already exist in the manager and is running
  18. // It then starts the newly added service
  19. func (m *AppManager) Add(service Service) {
  20. // check for existing service
  21. if currentService, ok := m.services[service.Name()]; ok {
  22. if currentService.Hash() == service.Hash() {
  23. return // the exact same service, no changes, so move along
  24. }
  25. currentService.Shutdown() //shutdown the listener since a new one is starting
  26. }
  27. m.services[service.Name()] = service
  28. //start the service!
  29. go m.serviceRun(service)
  30. }
  31. // Remove shutdowns the service by name and removes it from its current management list
  32. func (m *AppManager) Remove(name string) {
  33. if currentService, ok := m.services[name]; ok {
  34. currentService.Shutdown()
  35. }
  36. delete(m.services, name)
  37. }
  38. // Services returns all the current Services being managed
  39. func (m *AppManager) Services() []Service {
  40. values := []Service{}
  41. for _, value := range m.services {
  42. values = append(values, value)
  43. }
  44. return values
  45. }
  46. func (m *AppManager) serviceRun(service Service) {
  47. err := service.Run()
  48. if m.callback != nil {
  49. m.callback(service.Type(), service.Name(), err)
  50. }
  51. }