plugin.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package cluster
  2. import (
  3. "errors"
  4. "strings"
  5. "sync/atomic"
  6. "time"
  7. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  8. "github.com/langgenius/dify-plugin-daemon/internal/utils/cache"
  9. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  10. )
  11. type pluginLifeTime struct {
  12. lifetime entities.PluginRuntimeTimeLifeInterface
  13. last_scheduled_at time.Time
  14. }
  15. type pluginState struct {
  16. entities.PluginRuntimeState
  17. Identity string `json:"identity"`
  18. }
  19. // RegisterPlugin registers a plugin to the cluster, and start to be scheduled
  20. func (c *Cluster) RegisterPlugin(lifetime entities.PluginRuntimeTimeLifeInterface) error {
  21. identity, err := lifetime.Identity()
  22. if err != nil {
  23. return err
  24. }
  25. if c.plugins.Exits(identity) {
  26. return errors.New("plugin has been registered")
  27. }
  28. l := &pluginLifeTime{
  29. lifetime: lifetime,
  30. }
  31. lifetime.OnStop(func() {
  32. c.plugin_lock.Lock()
  33. c.plugins.Delete(identity)
  34. // remove plugin state
  35. c.doPluginStateUpdate(l)
  36. c.plugin_lock.Unlock()
  37. })
  38. c.plugin_lock.Lock()
  39. if !lifetime.Stopped() {
  40. c.plugins.Store(identity, l)
  41. // do plugin state update immediately
  42. err = c.doPluginStateUpdate(l)
  43. if err != nil {
  44. c.plugin_lock.Unlock()
  45. return err
  46. }
  47. }
  48. c.plugin_lock.Unlock()
  49. log.Info("start to schedule plugin %s", identity)
  50. return nil
  51. }
  52. const (
  53. PLUGIN_STATE_MAP_KEY = "plugin_state"
  54. )
  55. func (c *Cluster) getPluginStateKey(node_id string, plugin_id string) string {
  56. return node_id + ":" + plugin_id
  57. }
  58. func (c *Cluster) getScanPluginsByNodeKey(node_id string) string {
  59. return node_id + ":*"
  60. }
  61. func (c *Cluster) getScanPluginsByIdKey(plugin_id string) string {
  62. return "*:" + plugin_id
  63. }
  64. // SchedulePlugin schedules a plugin to the cluster
  65. // it will walk through the plugin state map and update all the states
  66. // as for the plugin has exited, normally, it will be removed automatically
  67. // but once a plugin is not removed, it will be gc by the master node
  68. func (c *Cluster) schedulePlugins() error {
  69. c.plugins.Range(func(key string, value *pluginLifeTime) bool {
  70. if time.Since(value.last_scheduled_at) < PLUGIN_SCHEDULER_INTERVAL {
  71. return true
  72. }
  73. // do plugin state update
  74. err := c.doPluginStateUpdate(value)
  75. if err != nil {
  76. log.Error("failed to update plugin state: %s", err.Error())
  77. }
  78. return true
  79. })
  80. return nil
  81. }
  82. // doPluginUpdate updates the plugin state and schedule the plugin
  83. func (c *Cluster) doPluginStateUpdate(lifetime *pluginLifeTime) error {
  84. state := lifetime.lifetime.RuntimeState()
  85. hash_identity, err := lifetime.lifetime.HashedIdentity()
  86. if err != nil {
  87. return err
  88. }
  89. identity, err := lifetime.lifetime.Identity()
  90. if err != nil {
  91. return err
  92. }
  93. schedule_state := &pluginState{
  94. Identity: identity,
  95. PluginRuntimeState: state,
  96. }
  97. state_key := c.getPluginStateKey(c.id, hash_identity)
  98. // check if the plugin has been removed
  99. if !c.plugins.Exits(identity) {
  100. // remove state
  101. err = c.removePluginState(c.id, hash_identity)
  102. if err != nil {
  103. return err
  104. }
  105. } else {
  106. // update plugin state
  107. schedule_state.ScheduledAt = &[]time.Time{time.Now()}[0]
  108. err = cache.SetMapOneField(PLUGIN_STATE_MAP_KEY, state_key, schedule_state)
  109. if err != nil {
  110. return err
  111. }
  112. lifetime.lifetime.UpdateScheduledAt(*schedule_state.ScheduledAt)
  113. }
  114. lifetime.last_scheduled_at = time.Now()
  115. return nil
  116. }
  117. func (c *Cluster) removePluginState(node_id string, hashed_identity string) error {
  118. err := cache.DelMapField(PLUGIN_STATE_MAP_KEY, c.getPluginStateKey(node_id, hashed_identity))
  119. if err != nil {
  120. return err
  121. }
  122. log.Info("plugin %s has been removed from node %s", hashed_identity, c.id)
  123. return nil
  124. }
  125. // forceGCNodePlugins will force garbage collect all the plugins on the node
  126. func (c *Cluster) forceGCNodePlugins(node_id string) error {
  127. return cache.ScanMapAsync[pluginState](
  128. PLUGIN_STATE_MAP_KEY,
  129. c.getScanPluginsByNodeKey(node_id),
  130. func(m map[string]pluginState) error {
  131. for _, plugin_state := range m {
  132. if err := c.forceGCNodePlugin(node_id, plugin_state.Identity); err != nil {
  133. return err
  134. }
  135. }
  136. return nil
  137. },
  138. )
  139. }
  140. // forceGCNodePlugin will force garbage collect the plugin on the node
  141. func (c *Cluster) forceGCNodePlugin(node_id string, plugin_id string) error {
  142. if node_id == c.id {
  143. c.plugin_lock.Lock()
  144. c.plugins.Delete(plugin_id)
  145. c.plugin_lock.Unlock()
  146. }
  147. if err := c.removePluginState(node_id, entities.HashedIdentity(plugin_id)); err != nil {
  148. return err
  149. }
  150. return nil
  151. }
  152. // forceGCPluginByNodePluginJoin will force garbage collect the plugin by node_plugin_join
  153. func (c *Cluster) forceGCPluginByNodePluginJoin(node_plugin_join string) error {
  154. return cache.DelMapField(PLUGIN_STATE_MAP_KEY, node_plugin_join)
  155. }
  156. func (c *Cluster) isPluginActive(state *pluginState) bool {
  157. return state != nil && state.ScheduledAt != nil && time.Since(*state.ScheduledAt) < 60*time.Second
  158. }
  159. func (c *Cluster) splitNodePluginJoin(node_plugin_join string) (node_id string, plugin_hashed_id string, err error) {
  160. split := strings.Split(node_plugin_join, ":")
  161. if len(split) != 2 {
  162. return "", "", errors.New("invalid node_plugin_join")
  163. }
  164. return split[0], split[1], nil
  165. }
  166. // autoGCPlugins will automatically garbage collect the plugins that are no longer active
  167. func (c *Cluster) autoGCPlugins() error {
  168. // skip if already in auto gc
  169. if atomic.LoadInt32(&c.is_in_auto_gc_plugins) == 1 {
  170. return nil
  171. }
  172. defer atomic.StoreInt32(&c.is_in_auto_gc_plugins, 0)
  173. return cache.ScanMapAsync[pluginState](
  174. PLUGIN_STATE_MAP_KEY,
  175. "*",
  176. func(m map[string]pluginState) error {
  177. for node_plugin_join, plugin_state := range m {
  178. if !c.isPluginActive(&plugin_state) {
  179. node_id, _, err := c.splitNodePluginJoin(node_plugin_join)
  180. if err != nil {
  181. return err
  182. }
  183. // force gc the plugin
  184. if err := c.forceGCNodePlugin(node_id, plugin_state.Identity); err != nil {
  185. return err
  186. }
  187. // one more time to force gc the plugin, there is a possibility
  188. // that the hash value of plugin's identity is not the same as the node_plugin_join
  189. // so we need to force gc the plugin by node_plugin_join again
  190. if err := c.forceGCPluginByNodePluginJoin(node_plugin_join); err != nil {
  191. return err
  192. }
  193. }
  194. }
  195. return nil
  196. },
  197. )
  198. }