rectify.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package rectify
  2. // this package is for watching the event bus and rectifying mismatches
  3. // between the desired and actual state
  4. import (
  5. "fmt"
  6. "goseg/broadcast"
  7. "goseg/config"
  8. "goseg/docker"
  9. "github.com/docker/docker/api/types/events"
  10. )
  11. // receives events via docker.EventBus
  12. // compares actual state to desired state
  13. func DockerSubscriptionHandler() {
  14. for {
  15. event := <-docker.EventBus
  16. dockerEvent, ok := event.Data.(events.Message)
  17. if !ok {
  18. config.Logger.Error("Failed to assert Docker event data type")
  19. continue
  20. }
  21. contName := dockerEvent.Actor.Attributes["name"]
  22. switch dockerEvent.Action {
  23. case "stop":
  24. config.Logger.Info(fmt.Sprintf("Docker: %s stopped", contName))
  25. if containerState, exists := config.GetContainerState()[contName]; exists {
  26. containerState.ActualStatus = "stopped"
  27. config.UpdateContainerState(contName, containerState)
  28. // start it again if this isn't what the user wants
  29. if containerState.DesiredStatus != "stopped" {
  30. docker.StartContainer(contName, containerState.Type)
  31. }
  32. broadcast.BroadcastToClients()
  33. }
  34. case "start":
  35. config.Logger.Info(fmt.Sprintf("Docker: %s started", contName))
  36. if containerState, exists := config.GetContainerState()[contName]; exists {
  37. containerState.ActualStatus = "running"
  38. config.UpdateContainerState(contName, containerState)
  39. broadcast.BroadcastToClients()
  40. }
  41. case "die":
  42. config.Logger.Warn(fmt.Sprintf("Docker: %s died!", contName))
  43. if containerState, exists := config.GetContainerState()[contName]; exists {
  44. containerState.ActualStatus = "died"
  45. // we don't want infinite restart loop
  46. containerState.DesiredStatus = "died"
  47. config.UpdateContainerState(contName, containerState)
  48. broadcast.BroadcastToClients()
  49. }
  50. default:
  51. if config.DebugMode == true {
  52. config.Logger.Info(fmt.Sprintf("%s event: %s", contName, dockerEvent.Action))
  53. }
  54. }
  55. }
  56. }