cluster.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package cluster
  2. import (
  3. "sync"
  4. "sync/atomic"
  5. "github.com/google/uuid"
  6. "github.com/langgenius/dify-plugin-daemon/internal/types/app"
  7. "github.com/langgenius/dify-plugin-daemon/internal/utils/mapping"
  8. )
  9. type Cluster struct {
  10. // id is the unique id of the cluster
  11. id string
  12. // i_am_master is the flag to indicate whether the current node is the master node
  13. i_am_master bool
  14. // port is the health check port of the cluster
  15. port uint16
  16. // plugins stores all the plugin life time of the cluster
  17. plugins mapping.Map[string, *pluginLifeTime]
  18. plugin_lock sync.RWMutex
  19. // nodes stores all the nodes of the cluster
  20. nodes mapping.Map[string, node]
  21. node_lock sync.RWMutex
  22. // signals for waiting for the cluster to stop
  23. stop_chan chan bool
  24. stopped *int32
  25. is_in_auto_gc_nodes int32
  26. is_in_auto_gc_plugins int32
  27. }
  28. func NewCluster(config *app.Config) *Cluster {
  29. return &Cluster{
  30. id: uuid.New().String(),
  31. port: uint16(config.ServerPort),
  32. stop_chan: make(chan bool),
  33. stopped: new(int32),
  34. }
  35. }
  36. func (c *Cluster) Launch() {
  37. go c.clusterLifetime()
  38. }
  39. func (c *Cluster) Close() error {
  40. if atomic.CompareAndSwapInt32(c.stopped, 0, 1) {
  41. close(c.stop_chan)
  42. }
  43. return nil
  44. }