rectify.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. contID := dockerEvent.Actor.ID
  25. contName := dockerEvent.Actor.Attributes["name"]
  26. switch dockerEvent.Action {
  27. case "stop":
  28. logger.Info(fmt.Sprintf("Docker: %s stopped", contName))
  29. if containerState, exists := config.GetContainerState()[contName]; exists {
  30. containerState.ActualStatus = "stopped"
  31. config.UpdateContainerState(contName, containerState)
  32. }
  33. case "start":
  34. logger.Info(fmt.Sprintf("Docker: %s started", contName))
  35. if containerState, exists := config.GetContainerState()[contName]; exists {
  36. containerState.ActualStatus = "started"
  37. config.UpdateContainerState(contName, containerState)
  38. }
  39. case "die":
  40. logger.Info(fmt.Sprintf("Docker: %s died!", contName))
  41. if containerState, exists := config.GetContainerState()[contName]; exists {
  42. containerState.ActualStatus = "died"
  43. containerState.DesiredStatus = "died"
  44. config.UpdateContainerState(contName, containerState)
  45. }
  46. default:
  47. logger.Info(fmt.Sprintf("%s event: %s", contName, dockerEvent.Action))
  48. }
  49. broadcast.BroadcastToClients()
  50. }
  51. }