manager.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. // platform, local or aws_lambda
  50. platform app.PlatformType
  51. }
  52. var (
  53. manager *PluginManager
  54. )
  55. func InitGlobalManager(oss oss.OSS, configuration *app.Config) *PluginManager {
  56. manager = &PluginManager{
  57. maxPluginPackageSize: configuration.MaxPluginPackageSize,
  58. pluginStoragePath: configuration.PluginInstalledPath,
  59. workingDirectory: configuration.PluginWorkingPath,
  60. mediaBucket: media_manager.NewAssetsBucket(
  61. oss,
  62. configuration.PluginMediaCachePath,
  63. configuration.PluginMediaCacheSize,
  64. ),
  65. packageBucket: media_manager.NewPackageBucket(
  66. oss,
  67. configuration.PluginPackageCachePath,
  68. ),
  69. installedBucket: media_manager.NewInstalledBucket(
  70. oss,
  71. configuration.PluginInstalledPath,
  72. ),
  73. localPluginLaunchingLock: lock.NewGranularityLock(),
  74. maxLaunchingLock: make(chan bool, 2), // by default, we allow 2 plugins launching at the same time
  75. pythonInterpreterPath: configuration.PythonInterpreterPath,
  76. platform: configuration.Platform,
  77. }
  78. return manager
  79. }
  80. func Manager() *PluginManager {
  81. return manager
  82. }
  83. func (p *PluginManager) Get(
  84. identity plugin_entities.PluginUniqueIdentifier,
  85. ) (plugin_entities.PluginLifetime, error) {
  86. if identity.RemoteLike() || p.platform == app.PLATFORM_LOCAL {
  87. // check if it's a debugging plugin or a local plugin
  88. if v, ok := p.m.Load(identity.String()); ok {
  89. return v, nil
  90. }
  91. return nil, errors.New("plugin not found")
  92. } else {
  93. // otherwise, use serverless runtime instead
  94. pluginSessionInterface, err := p.getServerlessPluginRuntime(identity)
  95. if err != nil {
  96. return nil, err
  97. }
  98. return pluginSessionInterface, nil
  99. }
  100. }
  101. func (p *PluginManager) GetAsset(id string) ([]byte, error) {
  102. return p.mediaBucket.Get(id)
  103. }
  104. func (p *PluginManager) Launch(configuration *app.Config) {
  105. log.Info("start plugin manager daemon...")
  106. // init redis client
  107. if err := cache.InitRedisClient(
  108. fmt.Sprintf("%s:%d", configuration.RedisHost, configuration.RedisPort),
  109. configuration.RedisPass,
  110. ); err != nil {
  111. log.Panic("init redis client failed: %s", err.Error())
  112. }
  113. invocation, err := real.NewDifyInvocationDaemon(
  114. configuration.DifyInnerApiURL, configuration.DifyInnerApiKey,
  115. )
  116. if err != nil {
  117. log.Panic("init dify invocation daemon failed: %s", err.Error())
  118. }
  119. p.backwardsInvocation = invocation
  120. // start local watcher
  121. if configuration.Platform == app.PLATFORM_LOCAL {
  122. p.startLocalWatcher()
  123. }
  124. // launch serverless connector
  125. if configuration.Platform == app.PLATFORM_AWS_LAMBDA {
  126. serverless.Init(configuration)
  127. }
  128. // start remote watcher
  129. p.startRemoteWatcher(configuration)
  130. }
  131. func (p *PluginManager) BackwardsInvocation() dify_invocation.BackwardsInvocation {
  132. return p.backwardsInvocation
  133. }
  134. func (p *PluginManager) SavePackage(plugin_unique_identifier plugin_entities.PluginUniqueIdentifier, pkg []byte) (
  135. *plugin_entities.PluginDeclaration, error,
  136. ) {
  137. // try to decode the package
  138. packageDecoder, err := decoder.NewZipPluginDecoder(pkg)
  139. if err != nil {
  140. return nil, err
  141. }
  142. // get the declaration
  143. declaration, err := packageDecoder.Manifest()
  144. if err != nil {
  145. return nil, err
  146. }
  147. // get the assets
  148. assets, err := packageDecoder.Assets()
  149. if err != nil {
  150. return nil, err
  151. }
  152. // remap the assets
  153. _, err = p.mediaBucket.RemapAssets(&declaration, assets)
  154. if err != nil {
  155. return nil, errors.Join(err, fmt.Errorf("failed to remap assets"))
  156. }
  157. uniqueIdentifier, err := packageDecoder.UniqueIdentity()
  158. if err != nil {
  159. return nil, err
  160. }
  161. // save to storage
  162. err = p.packageBucket.Save(plugin_unique_identifier.String(), pkg)
  163. if err != nil {
  164. return nil, err
  165. }
  166. // create plugin if not exists
  167. if _, err := db.GetOne[models.PluginDeclaration](
  168. db.Equal("plugin_unique_identifier", uniqueIdentifier.String()),
  169. ); err == db.ErrDatabaseNotFound {
  170. err = db.Create(&models.PluginDeclaration{
  171. PluginUniqueIdentifier: uniqueIdentifier.String(),
  172. PluginID: uniqueIdentifier.PluginID(),
  173. Declaration: declaration,
  174. })
  175. if err != nil {
  176. return nil, err
  177. }
  178. } else if err != nil {
  179. return nil, err
  180. }
  181. return &declaration, nil
  182. }
  183. func (p *PluginManager) GetPackage(
  184. plugin_unique_identifier plugin_entities.PluginUniqueIdentifier,
  185. ) ([]byte, error) {
  186. file, err := p.packageBucket.Get(plugin_unique_identifier.String())
  187. if err != nil {
  188. if os.IsNotExist(err) {
  189. return nil, errors.New("plugin package not found, please upload it firstly")
  190. }
  191. return nil, err
  192. }
  193. return file, nil
  194. }
  195. func (p *PluginManager) GetDeclaration(
  196. plugin_unique_identifier plugin_entities.PluginUniqueIdentifier,
  197. tenant_id string,
  198. runtime_type plugin_entities.PluginRuntimeType,
  199. ) (
  200. *plugin_entities.PluginDeclaration, error,
  201. ) {
  202. return helper.CombinedGetPluginDeclaration(
  203. plugin_unique_identifier, tenant_id, runtime_type,
  204. )
  205. }