rectify.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. func DockerSubscriptionHandler() {
  17. for {
  18. event := <-docker.EventBus
  19. dockerEvent, ok := event.Data.(events.Message) // assert the type
  20. if !ok {
  21. logger.Error("Failed to assert Docker event data type")
  22. continue
  23. }
  24. contName := dockerEvent.Actor.Attributes["name"]
  25. switch dockerEvent.Action {
  26. case "stop":
  27. logger.Info(fmt.Sprintf("Docker: %s stopped", contName))
  28. if containerState, exists := config.GetContainerState()[contName]; exists {
  29. containerState.ActualStatus = "stopped"
  30. config.UpdateContainerState(contName, containerState)
  31. }
  32. case "start":
  33. logger.Info(fmt.Sprintf("Docker: %s started", contName))
  34. if containerState, exists := config.GetContainerState()[contName]; exists {
  35. containerState.ActualStatus = "started"
  36. config.UpdateContainerState(contName, containerState)
  37. }
  38. case "die":
  39. logger.Info(fmt.Sprintf("Docker: %s died!", contName))
  40. if containerState, exists := config.GetContainerState()[contName]; exists {
  41. containerState.ActualStatus = "died"
  42. containerState.DesiredStatus = "died"
  43. config.UpdateContainerState(contName, containerState)
  44. }
  45. default:
  46. logger.Info(fmt.Sprintf("%s event: %s", contName, dockerEvent.Action))
  47. }
  48. broadcast.BroadcastToClients()
  49. }
  50. }