rectify.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. "log/slog"
  9. "os"
  10. "github.com/docker/docker/api/types/events"
  11. )
  12. var (
  13. logger = slog.New(slog.NewJSONHandler(os.Stdout, nil))
  14. )
  15. func DockerSubscriptionHandler() {
  16. for {
  17. event := <-docker.EventBus
  18. dockerEvent, ok := event.Data.(events.Message) // assert the type
  19. if !ok {
  20. logger.Error("Failed to assert Docker event data type")
  21. continue
  22. }
  23. contID := dockerEvent.Actor.ID
  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.GSContainers[contID]; exists {
  29. containerState.Status = "stopped"
  30. config.GSContainers[contID] = containerState
  31. }
  32. case "start":
  33. logger.Info(fmt.Sprintf("Docker: %s started", contName))
  34. if containerState, exists := config.GSContainers[contID]; exists {
  35. containerState.Status = "started"
  36. config.GSContainers[contID] = containerState
  37. }
  38. default:
  39. logger.Info(fmt.Sprintf("Docker event: %s", dockerEvent.Action))
  40. }
  41. broadcast.BroadcastToClients()
  42. }
  43. }