init.go 1.3 KB

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