watcher.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package plugin_manager
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "io/fs"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/basic_manager"
  13. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/local_manager"
  14. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/positive_manager"
  15. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/remote_manager"
  16. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_packager/decoder"
  17. "github.com/langgenius/dify-plugin-daemon/internal/types/app"
  18. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  19. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  20. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  21. )
  22. func (p *PluginManager) startLocalWatcher() {
  23. go func() {
  24. log.Info("start to handle new plugins in path: %s", p.pluginStoragePath)
  25. p.handleNewLocalPlugins()
  26. for range time.NewTicker(time.Second * 30).C {
  27. p.handleNewLocalPlugins()
  28. }
  29. }()
  30. }
  31. func (p *PluginManager) initRemotePluginServer(config *app.Config) {
  32. if p.remotePluginServer != nil {
  33. return
  34. }
  35. p.remotePluginServer = remote_manager.NewRemotePluginServer(config, p.mediaManager)
  36. }
  37. func (p *PluginManager) startRemoteWatcher(config *app.Config) {
  38. // launch TCP debugging server if enabled
  39. if config.PluginRemoteInstallingEnabled {
  40. p.initRemotePluginServer(config)
  41. go func() {
  42. err := p.remotePluginServer.Launch()
  43. if err != nil {
  44. log.Error("start remote plugin server failed: %s", err.Error())
  45. }
  46. }()
  47. go func() {
  48. p.remotePluginServer.Wrap(func(rpr plugin_entities.PluginFullDuplexLifetime) {
  49. identity, err := rpr.Identity()
  50. if err != nil {
  51. log.Error("get remote plugin identity failed: %s", err.Error())
  52. return
  53. }
  54. p.m.Store(identity.String(), rpr)
  55. routine.Submit(func() {
  56. defer func() {
  57. if err := recover(); err != nil {
  58. log.Error("plugin runtime error: %v", err)
  59. }
  60. p.m.Delete(identity.String())
  61. }()
  62. p.fullDuplexLifecycle(rpr, nil)
  63. })
  64. })
  65. }()
  66. }
  67. }
  68. func (p *PluginManager) handleNewLocalPlugins() {
  69. // walk through all plugins
  70. err := filepath.WalkDir(p.pluginStoragePath, func(path string, d fs.DirEntry, err error) error {
  71. if err != nil {
  72. return err
  73. }
  74. if !d.IsDir() {
  75. _, _, err := p.launchLocal(path)
  76. if err != nil {
  77. log.Error("launch local plugin failed: %s", err.Error())
  78. }
  79. }
  80. return nil
  81. })
  82. if err != nil {
  83. log.Error("walk through plugins failed: %s", err.Error())
  84. }
  85. }
  86. func (p *PluginManager) launchLocal(plugin_package_path string) (
  87. plugin_entities.PluginFullDuplexLifetime, <-chan error, error,
  88. ) {
  89. plugin, err := p.getLocalPluginRuntime(plugin_package_path)
  90. if err != nil {
  91. return nil, nil, err
  92. }
  93. identity, err := plugin.decoder.UniqueIdentity()
  94. if err != nil {
  95. return nil, nil, err
  96. }
  97. // lock launch process
  98. p.localPluginLaunchingLock.Lock(identity.String())
  99. defer p.localPluginLaunchingLock.Unlock(identity.String())
  100. // check if the plugin is already running
  101. if lifetime, ok := p.m.Load(identity.String()); ok {
  102. lifetime, ok := lifetime.(plugin_entities.PluginFullDuplexLifetime)
  103. if !ok {
  104. return nil, nil, fmt.Errorf("plugin runtime not found")
  105. }
  106. // returns a closed channel to indicate the plugin is already running, no more waiting is needed
  107. c := make(chan error)
  108. close(c)
  109. return lifetime, c, nil
  110. }
  111. // extract plugin
  112. decoder, ok := plugin.decoder.(*decoder.ZipPluginDecoder)
  113. if !ok {
  114. return nil, nil, fmt.Errorf("plugin decoder is not a zip decoder")
  115. }
  116. // check if the working directory exists, if not, create it, otherwise, launch it directly
  117. if _, err := os.Stat(plugin.runtime.State.WorkingPath); err != nil {
  118. if err := decoder.ExtractTo(plugin.runtime.State.WorkingPath); err != nil {
  119. return nil, nil, errors.Join(err, fmt.Errorf("extract plugin to working directory error"))
  120. }
  121. }
  122. success := false
  123. failed := func(message string) error {
  124. if !success {
  125. os.RemoveAll(plugin.runtime.State.WorkingPath)
  126. }
  127. return errors.New(message)
  128. }
  129. // get assets
  130. assets, err := plugin.decoder.Assets()
  131. if err != nil {
  132. return nil, nil, failed(err.Error())
  133. }
  134. local_plugin_runtime := local_manager.NewLocalPluginRuntime(p.pythonInterpreterPath)
  135. local_plugin_runtime.PluginRuntime = plugin.runtime
  136. local_plugin_runtime.PositivePluginRuntime = positive_manager.PositivePluginRuntime{
  137. BasicPluginRuntime: basic_manager.NewBasicPluginRuntime(p.mediaManager),
  138. LocalPackagePath: plugin.runtime.State.AbsolutePath,
  139. WorkingPath: plugin.runtime.State.WorkingPath,
  140. Decoder: plugin.decoder,
  141. }
  142. if err := local_plugin_runtime.RemapAssets(
  143. &local_plugin_runtime.Config,
  144. assets,
  145. ); err != nil {
  146. return nil, nil, failed(errors.Join(err, fmt.Errorf("remap plugin assets error")).Error())
  147. }
  148. success = true
  149. p.m.Store(identity.String(), local_plugin_runtime)
  150. launched_chan := make(chan error)
  151. // local plugin
  152. routine.Submit(func() {
  153. defer func() {
  154. if r := recover(); r != nil {
  155. log.Error("plugin runtime panic: %v", r)
  156. }
  157. p.m.Delete(identity.String())
  158. }()
  159. // add max launching lock to prevent too many plugins launching at the same time
  160. p.maxLaunchingLock <- true
  161. routine.Submit(func() {
  162. // wait for plugin launched
  163. <-launched_chan
  164. // release max launching lock
  165. <-p.maxLaunchingLock
  166. })
  167. p.fullDuplexLifecycle(local_plugin_runtime, launched_chan)
  168. })
  169. return local_plugin_runtime, launched_chan, nil
  170. }
  171. type pluginRuntimeWithDecoder struct {
  172. runtime plugin_entities.PluginRuntime
  173. decoder decoder.PluginDecoder
  174. }
  175. // extract plugin from package to working directory
  176. func (p *PluginManager) getLocalPluginRuntime(plugin_path string) (
  177. *pluginRuntimeWithDecoder,
  178. error,
  179. ) {
  180. pack, err := os.Open(plugin_path)
  181. if err != nil {
  182. return nil, errors.Join(err, fmt.Errorf("open plugin package error"))
  183. }
  184. defer pack.Close()
  185. if info, err := pack.Stat(); err != nil {
  186. return nil, errors.Join(err, fmt.Errorf("get plugin package info error"))
  187. } else if info.Size() > p.maxPluginPackageSize {
  188. log.Error("plugin package size is too large: %d", info.Size())
  189. return nil, errors.Join(err, fmt.Errorf("plugin package size is too large"))
  190. }
  191. plugin_zip, err := io.ReadAll(pack)
  192. if err != nil {
  193. return nil, errors.Join(err, fmt.Errorf("read plugin package error"))
  194. }
  195. decoder, err := decoder.NewZipPluginDecoder(plugin_zip)
  196. if err != nil {
  197. return nil, errors.Join(err, fmt.Errorf("create plugin decoder error"))
  198. }
  199. // get manifest
  200. manifest, err := decoder.Manifest()
  201. if err != nil {
  202. return nil, errors.Join(err, fmt.Errorf("get plugin manifest error"))
  203. }
  204. checksum, err := decoder.Checksum()
  205. if err != nil {
  206. return nil, errors.Join(err, fmt.Errorf("calculate checksum error"))
  207. }
  208. identity := manifest.Identity()
  209. identity = strings.ReplaceAll(identity, ":", "-")
  210. plugin_working_path := path.Join(p.workingDirectory, fmt.Sprintf("%s@%s", identity, checksum))
  211. return &pluginRuntimeWithDecoder{
  212. runtime: plugin_entities.PluginRuntime{
  213. Config: manifest,
  214. State: plugin_entities.PluginRuntimeState{
  215. Status: plugin_entities.PLUGIN_RUNTIME_STATUS_PENDING,
  216. Restarts: 0,
  217. AbsolutePath: plugin_path,
  218. WorkingPath: plugin_working_path,
  219. ActiveAt: nil,
  220. Verified: manifest.Verified,
  221. },
  222. },
  223. decoder: decoder,
  224. }, nil
  225. }