Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

plugin_service.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. import logging
  2. from collections.abc import Mapping, Sequence
  3. from mimetypes import guess_type
  4. from typing import Optional
  5. from pydantic import BaseModel
  6. from configs import dify_config
  7. from core.helper import marketplace
  8. from core.helper.download import download_with_size_limit
  9. from core.helper.marketplace import download_plugin_pkg
  10. from core.plugin.entities.bundle import PluginBundleDependency
  11. from core.plugin.entities.plugin import (
  12. GenericProviderID,
  13. PluginDeclaration,
  14. PluginEntity,
  15. PluginInstallation,
  16. PluginInstallationSource,
  17. )
  18. from core.plugin.entities.plugin_daemon import (
  19. PluginDecodeResponse,
  20. PluginInstallTask,
  21. PluginListResponse,
  22. PluginVerification,
  23. )
  24. from core.plugin.impl.asset import PluginAssetManager
  25. from core.plugin.impl.debugging import PluginDebuggingClient
  26. from core.plugin.impl.plugin import PluginInstaller
  27. from extensions.ext_redis import redis_client
  28. from services.errors.plugin import PluginInstallationForbiddenError
  29. from services.feature_service import FeatureService, PluginInstallationScope
  30. logger = logging.getLogger(__name__)
  31. class PluginService:
  32. class LatestPluginCache(BaseModel):
  33. plugin_id: str
  34. version: str
  35. unique_identifier: str
  36. REDIS_KEY_PREFIX = "plugin_service:latest_plugin:"
  37. REDIS_TTL = 60 * 5 # 5 minutes
  38. @staticmethod
  39. def fetch_latest_plugin_version(plugin_ids: Sequence[str]) -> Mapping[str, Optional[LatestPluginCache]]:
  40. """
  41. Fetch the latest plugin version
  42. """
  43. result: dict[str, Optional[PluginService.LatestPluginCache]] = {}
  44. try:
  45. cache_not_exists = []
  46. # Try to get from Redis first
  47. for plugin_id in plugin_ids:
  48. cached_data = redis_client.get(f"{PluginService.REDIS_KEY_PREFIX}{plugin_id}")
  49. if cached_data:
  50. result[plugin_id] = PluginService.LatestPluginCache.model_validate_json(cached_data)
  51. else:
  52. cache_not_exists.append(plugin_id)
  53. if cache_not_exists:
  54. manifests = {
  55. manifest.plugin_id: manifest
  56. for manifest in marketplace.batch_fetch_plugin_manifests(cache_not_exists)
  57. }
  58. for plugin_id, manifest in manifests.items():
  59. latest_plugin = PluginService.LatestPluginCache(
  60. plugin_id=plugin_id,
  61. version=manifest.latest_version,
  62. unique_identifier=manifest.latest_package_identifier,
  63. )
  64. # Store in Redis
  65. redis_client.setex(
  66. f"{PluginService.REDIS_KEY_PREFIX}{plugin_id}",
  67. PluginService.REDIS_TTL,
  68. latest_plugin.model_dump_json(),
  69. )
  70. result[plugin_id] = latest_plugin
  71. # pop plugin_id from cache_not_exists
  72. cache_not_exists.remove(plugin_id)
  73. for plugin_id in cache_not_exists:
  74. result[plugin_id] = None
  75. return result
  76. except Exception:
  77. logger.exception("failed to fetch latest plugin version")
  78. return result
  79. @staticmethod
  80. def _check_marketplace_only_permission():
  81. """
  82. Check if the marketplace only permission is enabled
  83. """
  84. features = FeatureService.get_system_features()
  85. if features.plugin_installation_permission.restrict_to_marketplace_only:
  86. raise PluginInstallationForbiddenError("Plugin installation is restricted to marketplace only")
  87. @staticmethod
  88. def _check_plugin_installation_scope(plugin_verification: Optional[PluginVerification]):
  89. """
  90. Check the plugin installation scope
  91. """
  92. features = FeatureService.get_system_features()
  93. match features.plugin_installation_permission.plugin_installation_scope:
  94. case PluginInstallationScope.OFFICIAL_ONLY:
  95. if (
  96. plugin_verification is None
  97. or plugin_verification.authorized_category != PluginVerification.AuthorizedCategory.Langgenius
  98. ):
  99. raise PluginInstallationForbiddenError("Plugin installation is restricted to official only")
  100. case PluginInstallationScope.OFFICIAL_AND_SPECIFIC_PARTNERS:
  101. if plugin_verification is None or plugin_verification.authorized_category not in [
  102. PluginVerification.AuthorizedCategory.Langgenius,
  103. PluginVerification.AuthorizedCategory.Partner,
  104. ]:
  105. raise PluginInstallationForbiddenError(
  106. "Plugin installation is restricted to official and specific partners"
  107. )
  108. case PluginInstallationScope.NONE:
  109. raise PluginInstallationForbiddenError("Installing plugins is not allowed")
  110. case PluginInstallationScope.ALL:
  111. pass
  112. @staticmethod
  113. def get_debugging_key(tenant_id: str) -> str:
  114. """
  115. get the debugging key of the tenant
  116. """
  117. manager = PluginDebuggingClient()
  118. return manager.get_debugging_key(tenant_id)
  119. @staticmethod
  120. def list_latest_versions(plugin_ids: Sequence[str]) -> Mapping[str, Optional[LatestPluginCache]]:
  121. """
  122. List the latest versions of the plugins
  123. """
  124. return PluginService.fetch_latest_plugin_version(plugin_ids)
  125. @staticmethod
  126. def list(tenant_id: str) -> list[PluginEntity]:
  127. """
  128. list all plugins of the tenant
  129. """
  130. manager = PluginInstaller()
  131. plugins = manager.list_plugins(tenant_id)
  132. return plugins
  133. @staticmethod
  134. def list_with_total(tenant_id: str, page: int, page_size: int) -> PluginListResponse:
  135. """
  136. list all plugins of the tenant
  137. """
  138. manager = PluginInstaller()
  139. plugins = manager.list_plugins_with_total(tenant_id, page, page_size)
  140. return plugins
  141. @staticmethod
  142. def list_installations_from_ids(tenant_id: str, ids: Sequence[str]) -> Sequence[PluginInstallation]:
  143. """
  144. List plugin installations from ids
  145. """
  146. manager = PluginInstaller()
  147. return manager.fetch_plugin_installation_by_ids(tenant_id, ids)
  148. @staticmethod
  149. def get_asset(tenant_id: str, asset_file: str) -> tuple[bytes, str]:
  150. """
  151. get the asset file of the plugin
  152. """
  153. manager = PluginAssetManager()
  154. # guess mime type
  155. mime_type, _ = guess_type(asset_file)
  156. return manager.fetch_asset(tenant_id, asset_file), mime_type or "application/octet-stream"
  157. @staticmethod
  158. def check_plugin_unique_identifier(tenant_id: str, plugin_unique_identifier: str) -> bool:
  159. """
  160. check if the plugin unique identifier is already installed by other tenant
  161. """
  162. manager = PluginInstaller()
  163. return manager.fetch_plugin_by_identifier(tenant_id, plugin_unique_identifier)
  164. @staticmethod
  165. def fetch_plugin_manifest(tenant_id: str, plugin_unique_identifier: str) -> PluginDeclaration:
  166. """
  167. Fetch plugin manifest
  168. """
  169. manager = PluginInstaller()
  170. return manager.fetch_plugin_manifest(tenant_id, plugin_unique_identifier)
  171. @staticmethod
  172. def fetch_install_tasks(tenant_id: str, page: int, page_size: int) -> Sequence[PluginInstallTask]:
  173. """
  174. Fetch plugin installation tasks
  175. """
  176. manager = PluginInstaller()
  177. return manager.fetch_plugin_installation_tasks(tenant_id, page, page_size)
  178. @staticmethod
  179. def fetch_install_task(tenant_id: str, task_id: str) -> PluginInstallTask:
  180. manager = PluginInstaller()
  181. return manager.fetch_plugin_installation_task(tenant_id, task_id)
  182. @staticmethod
  183. def delete_install_task(tenant_id: str, task_id: str) -> bool:
  184. """
  185. Delete a plugin installation task
  186. """
  187. manager = PluginInstaller()
  188. return manager.delete_plugin_installation_task(tenant_id, task_id)
  189. @staticmethod
  190. def delete_all_install_task_items(
  191. tenant_id: str,
  192. ) -> bool:
  193. """
  194. Delete all plugin installation task items
  195. """
  196. manager = PluginInstaller()
  197. return manager.delete_all_plugin_installation_task_items(tenant_id)
  198. @staticmethod
  199. def delete_install_task_item(tenant_id: str, task_id: str, identifier: str) -> bool:
  200. """
  201. Delete a plugin installation task item
  202. """
  203. manager = PluginInstaller()
  204. return manager.delete_plugin_installation_task_item(tenant_id, task_id, identifier)
  205. @staticmethod
  206. def upgrade_plugin_with_marketplace(
  207. tenant_id: str, original_plugin_unique_identifier: str, new_plugin_unique_identifier: str
  208. ):
  209. """
  210. Upgrade plugin with marketplace
  211. """
  212. if not dify_config.MARKETPLACE_ENABLED:
  213. raise ValueError("marketplace is not enabled")
  214. if original_plugin_unique_identifier == new_plugin_unique_identifier:
  215. raise ValueError("you should not upgrade plugin with the same plugin")
  216. # check if plugin pkg is already downloaded
  217. manager = PluginInstaller()
  218. features = FeatureService.get_system_features()
  219. try:
  220. manager.fetch_plugin_manifest(tenant_id, new_plugin_unique_identifier)
  221. # already downloaded, skip, and record install event
  222. marketplace.record_install_plugin_event(new_plugin_unique_identifier)
  223. except Exception:
  224. # plugin not installed, download and upload pkg
  225. pkg = download_plugin_pkg(new_plugin_unique_identifier)
  226. response = manager.upload_pkg(
  227. tenant_id,
  228. pkg,
  229. verify_signature=features.plugin_installation_permission.restrict_to_marketplace_only,
  230. )
  231. # check if the plugin is available to install
  232. PluginService._check_plugin_installation_scope(response.verification)
  233. return manager.upgrade_plugin(
  234. tenant_id,
  235. original_plugin_unique_identifier,
  236. new_plugin_unique_identifier,
  237. PluginInstallationSource.Marketplace,
  238. {
  239. "plugin_unique_identifier": new_plugin_unique_identifier,
  240. },
  241. )
  242. @staticmethod
  243. def upgrade_plugin_with_github(
  244. tenant_id: str,
  245. original_plugin_unique_identifier: str,
  246. new_plugin_unique_identifier: str,
  247. repo: str,
  248. version: str,
  249. package: str,
  250. ):
  251. """
  252. Upgrade plugin with github
  253. """
  254. PluginService._check_marketplace_only_permission()
  255. manager = PluginInstaller()
  256. return manager.upgrade_plugin(
  257. tenant_id,
  258. original_plugin_unique_identifier,
  259. new_plugin_unique_identifier,
  260. PluginInstallationSource.Github,
  261. {
  262. "repo": repo,
  263. "version": version,
  264. "package": package,
  265. },
  266. )
  267. @staticmethod
  268. def upload_pkg(tenant_id: str, pkg: bytes, verify_signature: bool = False) -> PluginDecodeResponse:
  269. """
  270. Upload plugin package files
  271. returns: plugin_unique_identifier
  272. """
  273. PluginService._check_marketplace_only_permission()
  274. manager = PluginInstaller()
  275. features = FeatureService.get_system_features()
  276. response = manager.upload_pkg(
  277. tenant_id,
  278. pkg,
  279. verify_signature=features.plugin_installation_permission.restrict_to_marketplace_only,
  280. )
  281. return response
  282. @staticmethod
  283. def upload_pkg_from_github(
  284. tenant_id: str, repo: str, version: str, package: str, verify_signature: bool = False
  285. ) -> PluginDecodeResponse:
  286. """
  287. Install plugin from github release package files,
  288. returns plugin_unique_identifier
  289. """
  290. PluginService._check_marketplace_only_permission()
  291. pkg = download_with_size_limit(
  292. f"https://github.com/{repo}/releases/download/{version}/{package}", dify_config.PLUGIN_MAX_PACKAGE_SIZE
  293. )
  294. features = FeatureService.get_system_features()
  295. manager = PluginInstaller()
  296. response = manager.upload_pkg(
  297. tenant_id,
  298. pkg,
  299. verify_signature=features.plugin_installation_permission.restrict_to_marketplace_only,
  300. )
  301. return response
  302. @staticmethod
  303. def upload_bundle(
  304. tenant_id: str, bundle: bytes, verify_signature: bool = False
  305. ) -> Sequence[PluginBundleDependency]:
  306. """
  307. Upload a plugin bundle and return the dependencies.
  308. """
  309. manager = PluginInstaller()
  310. PluginService._check_marketplace_only_permission()
  311. return manager.upload_bundle(tenant_id, bundle, verify_signature)
  312. @staticmethod
  313. def install_from_local_pkg(tenant_id: str, plugin_unique_identifiers: Sequence[str]):
  314. PluginService._check_marketplace_only_permission()
  315. manager = PluginInstaller()
  316. return manager.install_from_identifiers(
  317. tenant_id,
  318. plugin_unique_identifiers,
  319. PluginInstallationSource.Package,
  320. [{}],
  321. )
  322. @staticmethod
  323. def install_from_github(tenant_id: str, plugin_unique_identifier: str, repo: str, version: str, package: str):
  324. """
  325. Install plugin from github release package files,
  326. returns plugin_unique_identifier
  327. """
  328. PluginService._check_marketplace_only_permission()
  329. manager = PluginInstaller()
  330. return manager.install_from_identifiers(
  331. tenant_id,
  332. [plugin_unique_identifier],
  333. PluginInstallationSource.Github,
  334. [
  335. {
  336. "repo": repo,
  337. "version": version,
  338. "package": package,
  339. }
  340. ],
  341. )
  342. @staticmethod
  343. def fetch_marketplace_pkg(tenant_id: str, plugin_unique_identifier: str) -> PluginDeclaration:
  344. """
  345. Fetch marketplace package
  346. """
  347. if not dify_config.MARKETPLACE_ENABLED:
  348. raise ValueError("marketplace is not enabled")
  349. features = FeatureService.get_system_features()
  350. manager = PluginInstaller()
  351. try:
  352. declaration = manager.fetch_plugin_manifest(tenant_id, plugin_unique_identifier)
  353. except Exception:
  354. pkg = download_plugin_pkg(plugin_unique_identifier)
  355. response = manager.upload_pkg(
  356. tenant_id,
  357. pkg,
  358. verify_signature=features.plugin_installation_permission.restrict_to_marketplace_only,
  359. )
  360. # check if the plugin is available to install
  361. PluginService._check_plugin_installation_scope(response.verification)
  362. declaration = response.manifest
  363. return declaration
  364. @staticmethod
  365. def install_from_marketplace_pkg(tenant_id: str, plugin_unique_identifiers: Sequence[str]):
  366. """
  367. Install plugin from marketplace package files,
  368. returns installation task id
  369. """
  370. if not dify_config.MARKETPLACE_ENABLED:
  371. raise ValueError("marketplace is not enabled")
  372. manager = PluginInstaller()
  373. features = FeatureService.get_system_features()
  374. # check if already downloaded
  375. for plugin_unique_identifier in plugin_unique_identifiers:
  376. try:
  377. manager.fetch_plugin_manifest(tenant_id, plugin_unique_identifier)
  378. plugin_decode_response = manager.decode_plugin_from_identifier(tenant_id, plugin_unique_identifier)
  379. # check if the plugin is available to install
  380. PluginService._check_plugin_installation_scope(plugin_decode_response.verification)
  381. # already downloaded, skip
  382. except Exception:
  383. # plugin not installed, download and upload pkg
  384. pkg = download_plugin_pkg(plugin_unique_identifier)
  385. response = manager.upload_pkg(
  386. tenant_id,
  387. pkg,
  388. verify_signature=features.plugin_installation_permission.restrict_to_marketplace_only,
  389. )
  390. # check if the plugin is available to install
  391. PluginService._check_plugin_installation_scope(response.verification)
  392. return manager.install_from_identifiers(
  393. tenant_id,
  394. plugin_unique_identifiers,
  395. PluginInstallationSource.Marketplace,
  396. [
  397. {
  398. "plugin_unique_identifier": plugin_unique_identifier,
  399. }
  400. for plugin_unique_identifier in plugin_unique_identifiers
  401. ],
  402. )
  403. @staticmethod
  404. def uninstall(tenant_id: str, plugin_installation_id: str) -> bool:
  405. manager = PluginInstaller()
  406. return manager.uninstall(tenant_id, plugin_installation_id)
  407. @staticmethod
  408. def check_tools_existence(tenant_id: str, provider_ids: Sequence[GenericProviderID]) -> Sequence[bool]:
  409. """
  410. Check if the tools exist
  411. """
  412. manager = PluginInstaller()
  413. return manager.check_tools_existence(tenant_id, provider_ids)