hooks.go 7.3 KB

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