watcher.go 7.5 KB

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