rectify.go 1.6 KB

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