manager.go 7.3 KB

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