rectify.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "log/slog"
  10. "os"
  11. "github.com/docker/docker/api/types/events"
  12. )
  13. var (
  14. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  15. )
  16. // receives events via docker.EventBus
  17. // compares actual state to desired state
  18. func DockerSubscriptionHandler() {
  19. for {
  20. event := <-docker.EventBus
  21. dockerEvent, ok := event.Data.(events.Message)
  22. if !ok {
  23. logger.Error("Failed to assert Docker event data type")
  24. continue
  25. }
  26. contName := dockerEvent.Actor.Attributes["name"]
  27. switch dockerEvent.Action {
  28. case "stop":
  29. logger.Info(fmt.Sprintf("Docker: %s stopped", contName))
  30. if containerState, exists := config.GetContainerState()[contName]; exists {
  31. containerState.ActualStatus = "stopped"
  32. config.UpdateContainerState(contName, containerState)
  33. // start it again if this isn't what the user wants
  34. if containerState.DesiredStatus != "stopped" {
  35. docker.StartContainer(contName, containerState.Type)
  36. }
  37. broadcast.BroadcastToClients()
  38. }
  39. case "start":
  40. logger.Info(fmt.Sprintf("Docker: %s started", contName))
  41. if containerState, exists := config.GetContainerState()[contName]; exists {
  42. containerState.ActualStatus = "running"
  43. config.UpdateContainerState(contName, containerState)
  44. broadcast.BroadcastToClients()
  45. }
  46. case "die":
  47. logger.Warn(fmt.Sprintf("Docker: %s died!", contName))
  48. if containerState, exists := config.GetContainerState()[contName]; exists {
  49. containerState.ActualStatus = "died"
  50. // we don't want infinite restart loop
  51. containerState.DesiredStatus = "died"
  52. config.UpdateContainerState(contName, containerState)
  53. broadcast.BroadcastToClients()
  54. }
  55. default:
  56. if config.DebugMode == true {
  57. logger.Info(fmt.Sprintf("%s event: %s", contName, dockerEvent.Action))
  58. }
  59. }
  60. }
  61. }