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