hooks.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package remote_manager
  2. import (
  3. "encoding/hex"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/basic_manager"
  8. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/media_manager"
  9. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  10. "github.com/langgenius/dify-plugin-daemon/internal/utils/cache"
  11. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  12. "github.com/langgenius/dify-plugin-daemon/internal/utils/parser"
  13. "github.com/langgenius/dify-plugin-daemon/internal/utils/stream"
  14. "github.com/panjf2000/gnet/v2"
  15. )
  16. var (
  17. _mode pluginRuntimeMode
  18. )
  19. type DifyServer struct {
  20. gnet.BuiltinEventEngine
  21. engine gnet.Engine
  22. mediaManager *media_manager.MediaManager
  23. // listening address
  24. addr string
  25. port uint16
  26. // enabled multicore
  27. multicore bool
  28. // event loop count
  29. num_loops int
  30. // read new connections
  31. response *stream.Stream[*RemotePluginRuntime]
  32. plugins map[int]*RemotePluginRuntime
  33. plugins_lock *sync.RWMutex
  34. shutdown_chan chan bool
  35. }
  36. func (s *DifyServer) OnBoot(c gnet.Engine) (action gnet.Action) {
  37. s.engine = c
  38. return gnet.None
  39. }
  40. func (s *DifyServer) OnOpen(c gnet.Conn) (out []byte, action gnet.Action) {
  41. // new plugin connected
  42. c.SetContext(&codec{})
  43. runtime := &RemotePluginRuntime{
  44. BasicPluginRuntime: basic_manager.NewBasicPluginRuntime(
  45. s.mediaManager,
  46. ),
  47. conn: c,
  48. response: stream.NewStreamResponse[[]byte](512),
  49. callbacks: make(map[string][]func([]byte)),
  50. callbacks_lock: &sync.RWMutex{},
  51. shutdown_chan: make(chan bool),
  52. alive: true,
  53. }
  54. // store plugin runtime
  55. s.plugins_lock.Lock()
  56. s.plugins[c.Fd()] = runtime
  57. s.plugins_lock.Unlock()
  58. // start a timer to check if handshake is completed in 10 seconds
  59. time.AfterFunc(time.Second*10, func() {
  60. if !runtime.handshake {
  61. // close connection
  62. c.Close()
  63. }
  64. })
  65. // verified
  66. verified := true
  67. if verified {
  68. return nil, gnet.None
  69. }
  70. return nil, gnet.Close
  71. }
  72. func (s *DifyServer) OnClose(c gnet.Conn, err error) (action gnet.Action) {
  73. // plugin disconnected
  74. s.plugins_lock.Lock()
  75. plugin := s.plugins[c.Fd()]
  76. delete(s.plugins, c.Fd())
  77. s.plugins_lock.Unlock()
  78. // close plugin
  79. plugin.onDisconnected()
  80. // clear assets
  81. plugin.ClearAssets()
  82. // uninstall plugin
  83. if plugin.assets_transferred {
  84. if _mode != _PLUGIN_RUNTIME_MODE_CI {
  85. if err := plugin.Unregister(); err != nil {
  86. log.Error("unregister plugin failed, error: %v", err)
  87. }
  88. }
  89. }
  90. return gnet.None
  91. }
  92. func (s *DifyServer) OnShutdown(c gnet.Engine) {
  93. close(s.shutdown_chan)
  94. }
  95. func (s *DifyServer) OnTraffic(c gnet.Conn) (action gnet.Action) {
  96. codec := c.Context().(*codec)
  97. messages, err := codec.Decode(c)
  98. if err != nil {
  99. return gnet.Close
  100. }
  101. // get plugin runtime
  102. s.plugins_lock.RLock()
  103. runtime, ok := s.plugins[c.Fd()]
  104. s.plugins_lock.RUnlock()
  105. if !ok {
  106. return gnet.Close
  107. }
  108. // handle messages
  109. for _, message := range messages {
  110. if len(message) == 0 {
  111. continue
  112. }
  113. s.onMessage(runtime, message)
  114. }
  115. return gnet.None
  116. }
  117. func (s *DifyServer) onMessage(runtime *RemotePluginRuntime, message []byte) {
  118. // handle message
  119. if runtime.handshake_failed {
  120. // do nothing if handshake has failed
  121. return
  122. }
  123. close := func(message []byte) {
  124. if atomic.CompareAndSwapInt32(&runtime.closed, 0, 1) {
  125. runtime.conn.Write(message)
  126. runtime.conn.Close()
  127. }
  128. }
  129. if !runtime.handshake {
  130. key := string(message)
  131. info, err := GetConnectionInfo(key)
  132. if err == cache.ErrNotFound {
  133. // close connection if handshake failed
  134. close([]byte("handshake failed, invalid key\n"))
  135. runtime.handshake_failed = true
  136. return
  137. } else if err != nil {
  138. // close connection if handshake failed
  139. close([]byte("internal error\n"))
  140. return
  141. }
  142. runtime.tenant_id = info.TenantId
  143. // handshake completed
  144. runtime.handshake = true
  145. } else if !runtime.registration_transferred {
  146. // process handle shake if not completed
  147. declaration, err := parser.UnmarshalJsonBytes[plugin_entities.PluginDeclaration](message)
  148. if err != nil {
  149. // close connection if handshake failed
  150. close([]byte("handshake failed, invalid plugin declaration\n"))
  151. return
  152. }
  153. runtime.Config = declaration
  154. // registration transferred
  155. runtime.registration_transferred = true
  156. } else if !runtime.tools_registration_transferred {
  157. tools, err := parser.UnmarshalJsonBytes2Slice[plugin_entities.ToolProviderDeclaration](message)
  158. if err != nil {
  159. log.Error("tools register failed, error: %v", err)
  160. close([]byte("tools register failed, invalid tools declaration\n"))
  161. return
  162. }
  163. runtime.tools_registration_transferred = true
  164. if len(tools) > 0 {
  165. declaration := runtime.Config
  166. declaration.Tool = &tools[0]
  167. runtime.Config = declaration
  168. }
  169. } else if !runtime.models_registration_transferred {
  170. models, err := parser.UnmarshalJsonBytes2Slice[plugin_entities.ModelProviderDeclaration](message)
  171. if err != nil {
  172. log.Error("models register failed, error: %v", err)
  173. close([]byte("models register failed, invalid models declaration\n"))
  174. return
  175. }
  176. runtime.models_registration_transferred = true
  177. if len(models) > 0 {
  178. declaration := runtime.Config
  179. declaration.Model = &models[0]
  180. runtime.Config = declaration
  181. }
  182. } else if !runtime.endpoints_registration_transferred {
  183. endpoints, err := parser.UnmarshalJsonBytes2Slice[plugin_entities.EndpointProviderDeclaration](message)
  184. if err != nil {
  185. log.Error("endpoints register failed, error: %v", err)
  186. close([]byte("endpoints register failed, invalid endpoints declaration\n"))
  187. return
  188. }
  189. runtime.endpoints_registration_transferred = true
  190. if len(endpoints) > 0 {
  191. declaration := runtime.Config
  192. declaration.Endpoint = &endpoints[0]
  193. runtime.Config = declaration
  194. }
  195. } else if !runtime.assets_transferred {
  196. assets, err := parser.UnmarshalJsonBytes2Slice[plugin_entities.RemoteAssetPayload](message)
  197. if err != nil {
  198. log.Error("assets register failed, error: %v", err)
  199. close([]byte("assets register failed, invalid assets declaration\n"))
  200. return
  201. }
  202. files := make(map[string][]byte)
  203. for _, asset := range assets {
  204. files[asset.Filename], err = hex.DecodeString(asset.Data)
  205. if err != nil {
  206. log.Error("assets decode failed, error: %v", err)
  207. close([]byte("assets decode failed, invalid assets data, cannot decode file\n"))
  208. return
  209. }
  210. }
  211. // remap assets
  212. if err := runtime.RemapAssets(&runtime.Config, files); err != nil {
  213. log.Error("assets remap failed, error: %v", err)
  214. close([]byte("assets remap failed, invalid assets data, cannot remap\n"))
  215. return
  216. }
  217. runtime.assets_transferred = true
  218. runtime.checksum = runtime.calculateChecksum()
  219. runtime.InitState()
  220. runtime.SetActiveAt(time.Now())
  221. // trigger registration event
  222. if err := runtime.Register(); err != nil {
  223. log.Error("register failed, error: %v", err)
  224. close([]byte("register failed, cannot register\n"))
  225. return
  226. }
  227. // publish runtime to watcher
  228. s.response.Write(runtime)
  229. } else {
  230. // continue handle messages if handshake completed
  231. runtime.response.Write(message)
  232. }
  233. }