rectify.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. }
  38. case "start":
  39. logger.Info(fmt.Sprintf("Docker: %s started", contName))
  40. if containerState, exists := config.GetContainerState()[contName]; exists {
  41. containerState.ActualStatus = "running"
  42. config.UpdateContainerState(contName, containerState)
  43. }
  44. case "die":
  45. logger.Warn(fmt.Sprintf("Docker: %s died!", contName))
  46. if containerState, exists := config.GetContainerState()[contName]; exists {
  47. containerState.ActualStatus = "died"
  48. // we don't want infinite restart loop
  49. containerState.DesiredStatus = "died"
  50. config.UpdateContainerState(contName, containerState)
  51. }
  52. default:
  53. logger.Info(fmt.Sprintf("%s event: %s", contName, dockerEvent.Action))
  54. }
  55. broadcast.BroadcastToClients()
  56. }
  57. }