manager.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package plugin_manager
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "github.com/langgenius/dify-plugin-daemon/internal/core/dify_invocation"
  7. "github.com/langgenius/dify-plugin-daemon/internal/core/dify_invocation/real"
  8. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/media_manager"
  9. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/remote_manager"
  10. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_manager/serverless"
  11. "github.com/langgenius/dify-plugin-daemon/internal/core/plugin_packager/decoder"
  12. "github.com/langgenius/dify-plugin-daemon/internal/db"
  13. "github.com/langgenius/dify-plugin-daemon/internal/oss"
  14. "github.com/langgenius/dify-plugin-daemon/internal/types/app"
  15. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  16. "github.com/langgenius/dify-plugin-daemon/internal/types/models"
  17. "github.com/langgenius/dify-plugin-daemon/internal/utils/cache"
  18. "github.com/langgenius/dify-plugin-daemon/internal/utils/cache/helper"
  19. "github.com/langgenius/dify-plugin-daemon/internal/utils/lock"
  20. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  21. "github.com/langgenius/dify-plugin-daemon/internal/utils/mapping"
  22. )
  23. type PluginManager struct {
  24. m mapping.Map[string, plugin_entities.PluginLifetime]
  25. // max size of a plugin package
  26. maxPluginPackageSize int64
  27. // where the plugin finally running
  28. workingDirectory string
  29. // where the plugin finally installed but not running
  30. pluginStoragePath string
  31. // mediaBucket is used to manage media files like plugin icons, images, etc.
  32. mediaBucket *media_manager.MediaBucket
  33. // packageBucket is used to manage plugin packages, all the packages uploaded by users will be saved here
  34. packageBucket *media_manager.PackageBucket
  35. // installedBucket is used to manage installed plugins, all the installed plugins will be saved here
  36. installedBucket *media_manager.InstalledBucket
  37. // register plugin
  38. pluginRegisters []func(lifetime plugin_entities.PluginLifetime) error
  39. // localPluginLaunchingLock is a lock to launch local plugins
  40. localPluginLaunchingLock *lock.GranularityLock
  41. // backwardsInvocation is a handle to invoke dify
  42. backwardsInvocation dify_invocation.BackwardsInvocation
  43. // python interpreter path
  44. pythonInterpreterPath string
  45. // remote plugin server
  46. remotePluginServer remote_manager.RemotePluginServerInterface
  47. // max launching lock to prevent too many plugins launching at the same time
  48. maxLaunchingLock chan bool
  49. }
  50. var (
  51. manager *PluginManager
  52. )
  53. func InitGlobalManager(oss oss.OSS, configuration *app.Config) *PluginManager {
  54. manager = &PluginManager{
  55. maxPluginPackageSize: configuration.MaxPluginPackageSize,
  56. pluginStoragePath: configuration.PluginInstalledPath,
  57. workingDirectory: configuration.PluginWorkingPath,
  58. mediaBucket: media_manager.NewAssetsBucket(
  59. oss,
  60. configuration.PluginMediaCachePath,
  61. configuration.PluginMediaCacheSize,
  62. ),
  63. packageBucket: media_manager.NewPackageBucket(
  64. oss,
  65. configuration.PluginPackageCachePath,
  66. ),
  67. installedBucket: media_manager.NewInstalledBucket(
  68. oss,
  69. configuration.PluginInstalledPath,
  70. ),
  71. localPluginLaunchingLock: lock.NewGranularityLock(),
  72. maxLaunchingLock: make(chan bool, 2), // by default, we allow 2 plugins launching at the same time
  73. pythonInterpreterPath: configuration.PythonInterpreterPath,
  74. }
  75. return manager
  76. }
  77. func Manager() *PluginManager {
  78. return manager
  79. }
  80. func (p *PluginManager) Get(
  81. identity plugin_entities.PluginUniqueIdentifier,
  82. ) (plugin_entities.PluginLifetime, error) {
  83. if v, ok := p.m.Load(identity.String()); ok {
  84. return v, nil
  85. }
  86. // check if plugin is a serverless runtime
  87. pluginSessionInterface, err := p.getServerlessPluginRuntime(identity)
  88. if err != nil {
  89. return nil, err
  90. }
  91. return pluginSessionInterface, nil
  92. }
  93. func (p *PluginManager) GetAsset(id string) ([]byte, error) {
  94. return p.mediaBucket.Get(id)
  95. }
  96. func (p *PluginManager) Launch(configuration *app.Config) {
  97. log.Info("start plugin manager daemon...")
  98. // init redis client
  99. if err := cache.InitRedisClient(
  100. fmt.Sprintf("%s:%d", configuration.RedisHost, configuration.RedisPort),
  101. configuration.RedisPass,
  102. ); err != nil {
  103. log.Panic("init redis client failed: %s", err.Error())
  104. }
  105. invocation, err := real.NewDifyInvocationDaemon(
  106. configuration.DifyInnerApiURL, configuration.DifyInnerApiKey,
  107. )
  108. if err != nil {
  109. log.Panic("init dify invocation daemon failed: %s", err.Error())
  110. }
  111. p.backwardsInvocation = invocation
  112. // start local watcher
  113. if configuration.Platform == app.PLATFORM_LOCAL {
  114. p.startLocalWatcher()
  115. }
  116. // launch serverless connector
  117. if configuration.Platform == app.PLATFORM_AWS_LAMBDA {
  118. serverless.Init(configuration)
  119. }
  120. // start remote watcher
  121. p.startRemoteWatcher(configuration)
  122. }
  123. func (p *PluginManager) BackwardsInvocation() dify_invocation.BackwardsInvocation {
  124. return p.backwardsInvocation
  125. }
  126. func (p *PluginManager) SavePackage(plugin_unique_identifier plugin_entities.PluginUniqueIdentifier, pkg []byte) (
  127. *plugin_entities.PluginDeclaration, error,
  128. ) {
  129. // try to decode the package
  130. packageDecoder, err := decoder.NewZipPluginDecoder(pkg)
  131. if err != nil {
  132. return nil, err
  133. }
  134. // get the declaration
  135. declaration, err := packageDecoder.Manifest()
  136. if err != nil {
  137. return nil, err
  138. }
  139. // get the assets
  140. assets, err := packageDecoder.Assets()
  141. if err != nil {
  142. return nil, err
  143. }
  144. // remap the assets
  145. _, err = p.mediaBucket.RemapAssets(&declaration, assets)
  146. if err != nil {
  147. return nil, errors.Join(err, fmt.Errorf("failed to remap assets"))
  148. }
  149. uniqueIdentifier, err := packageDecoder.UniqueIdentity()
  150. if err != nil {
  151. return nil, err
  152. }
  153. // save to storage
  154. err = p.packageBucket.Save(plugin_unique_identifier.String(), pkg)
  155. if err != nil {
  156. return nil, err
  157. }
  158. // create plugin if not exists
  159. if _, err := db.GetOne[models.PluginDeclaration](
  160. db.Equal("plugin_unique_identifier", uniqueIdentifier.String()),
  161. ); err == db.ErrDatabaseNotFound {
  162. err = db.Create(&models.PluginDeclaration{
  163. PluginUniqueIdentifier: uniqueIdentifier.String(),
  164. PluginID: uniqueIdentifier.PluginID(),
  165. Declaration: declaration,
  166. })
  167. if err != nil {
  168. return nil, err
  169. }
  170. } else if err != nil {
  171. return nil, err
  172. }
  173. return &declaration, nil
  174. }
  175. func (p *PluginManager) GetPackage(
  176. plugin_unique_identifier plugin_entities.PluginUniqueIdentifier,
  177. ) ([]byte, error) {
  178. file, err := p.packageBucket.Get(plugin_unique_identifier.String())
  179. if err != nil {
  180. if os.IsNotExist(err) {
  181. return nil, errors.New("plugin package not found, please upload it firstly")
  182. }
  183. return nil, err
  184. }
  185. return file, nil
  186. }
  187. func (p *PluginManager) GetDeclaration(
  188. plugin_unique_identifier plugin_entities.PluginUniqueIdentifier,
  189. tenant_id string,
  190. runtime_type plugin_entities.PluginRuntimeType,
  191. ) (
  192. *plugin_entities.PluginDeclaration, error,
  193. ) {
  194. return helper.CombinedGetPluginDeclaration(
  195. plugin_unique_identifier, tenant_id, runtime_type,
  196. )
  197. }