rectify.go 1.2 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. 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.GSContainers[contID]; exists {
  30. containerState.Status = "stopped"
  31. config.GSContainers[contID] = containerState
  32. }
  33. case "start":
  34. logger.Info(fmt.Sprintf("Docker: %s started", contName))
  35. if containerState, exists := config.GSContainers[contID]; exists {
  36. containerState.Status = "started"
  37. config.GSContainers[contID] = containerState
  38. }
  39. default:
  40. logger.Info(fmt.Sprintf("%s event: %s", contName, dockerEvent.Action))
  41. }
  42. broadcast.BroadcastToClients()
  43. }
  44. }