Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

plugin_migration.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import datetime
  2. import json
  3. import logging
  4. import time
  5. from collections.abc import Mapping, Sequence
  6. from concurrent.futures import ThreadPoolExecutor
  7. from pathlib import Path
  8. from typing import Any, Optional
  9. from uuid import uuid4
  10. import click
  11. import sqlalchemy as sa
  12. import tqdm
  13. from flask import Flask, current_app
  14. from sqlalchemy.orm import Session
  15. from core.agent.entities import AgentToolEntity
  16. from core.helper import marketplace
  17. from core.plugin.entities.plugin import ModelProviderID, PluginInstallationSource, ToolProviderID
  18. from core.plugin.entities.plugin_daemon import PluginInstallTaskStatus
  19. from core.plugin.impl.plugin import PluginInstaller
  20. from core.tools.entities.tool_entities import ToolProviderType
  21. from models.account import Tenant
  22. from models.engine import db
  23. from models.model import App, AppMode, AppModelConfig
  24. from models.tools import BuiltinToolProvider
  25. from models.workflow import Workflow
  26. logger = logging.getLogger(__name__)
  27. excluded_providers = ["time", "audio", "code", "webscraper"]
  28. class PluginMigration:
  29. @classmethod
  30. def extract_plugins(cls, filepath: str, workers: int) -> None:
  31. """
  32. Migrate plugin.
  33. """
  34. from threading import Lock
  35. click.echo(click.style("Migrating models/tools to new plugin Mechanism", fg="white"))
  36. ended_at = datetime.datetime.now()
  37. started_at = datetime.datetime(2023, 4, 3, 8, 59, 24)
  38. current_time = started_at
  39. with Session(db.engine) as session:
  40. total_tenant_count = session.query(Tenant.id).count()
  41. click.echo(click.style(f"Total tenant count: {total_tenant_count}", fg="white"))
  42. handled_tenant_count = 0
  43. file_lock = Lock()
  44. counter_lock = Lock()
  45. thread_pool = ThreadPoolExecutor(max_workers=workers)
  46. def process_tenant(flask_app: Flask, tenant_id: str) -> None:
  47. with flask_app.app_context():
  48. nonlocal handled_tenant_count
  49. try:
  50. plugins = cls.extract_installed_plugin_ids(tenant_id)
  51. # Use lock when writing to file
  52. with file_lock:
  53. with open(filepath, "a") as f:
  54. f.write(json.dumps({"tenant_id": tenant_id, "plugins": plugins}) + "\n")
  55. # Use lock when updating counter
  56. with counter_lock:
  57. nonlocal handled_tenant_count
  58. handled_tenant_count += 1
  59. click.echo(
  60. click.style(
  61. f"[{datetime.datetime.now()}] "
  62. f"Processed {handled_tenant_count} tenants "
  63. f"({(handled_tenant_count / total_tenant_count) * 100:.1f}%), "
  64. f"{handled_tenant_count}/{total_tenant_count}",
  65. fg="green",
  66. )
  67. )
  68. except Exception:
  69. logger.exception("Failed to process tenant %s", tenant_id)
  70. futures = []
  71. while current_time < ended_at:
  72. click.echo(click.style(f"Current time: {current_time}, Started at: {datetime.datetime.now()}", fg="white"))
  73. # Initial interval of 1 day, will be dynamically adjusted based on tenant count
  74. interval = datetime.timedelta(days=1)
  75. # Process tenants in this batch
  76. with Session(db.engine) as session:
  77. # Calculate tenant count in next batch with current interval
  78. # Try different intervals until we find one with a reasonable tenant count
  79. test_intervals = [
  80. datetime.timedelta(days=1),
  81. datetime.timedelta(hours=12),
  82. datetime.timedelta(hours=6),
  83. datetime.timedelta(hours=3),
  84. datetime.timedelta(hours=1),
  85. ]
  86. for test_interval in test_intervals:
  87. tenant_count = (
  88. session.query(Tenant.id)
  89. .where(Tenant.created_at.between(current_time, current_time + test_interval))
  90. .count()
  91. )
  92. if tenant_count <= 100:
  93. interval = test_interval
  94. break
  95. else:
  96. # If all intervals have too many tenants, use minimum interval
  97. interval = datetime.timedelta(hours=1)
  98. # Adjust interval to target ~100 tenants per batch
  99. if tenant_count > 0:
  100. # Scale interval based on ratio to target count
  101. interval = min(
  102. datetime.timedelta(days=1), # Max 1 day
  103. max(
  104. datetime.timedelta(hours=1), # Min 1 hour
  105. interval * (100 / tenant_count), # Scale to target 100
  106. ),
  107. )
  108. batch_end = min(current_time + interval, ended_at)
  109. rs = (
  110. session.query(Tenant.id)
  111. .where(Tenant.created_at.between(current_time, batch_end))
  112. .order_by(Tenant.created_at)
  113. )
  114. tenants = []
  115. for row in rs:
  116. tenant_id = str(row.id)
  117. try:
  118. tenants.append(tenant_id)
  119. except Exception:
  120. logger.exception("Failed to process tenant %s", tenant_id)
  121. continue
  122. futures.append(
  123. thread_pool.submit(
  124. process_tenant,
  125. current_app._get_current_object(), # type: ignore[attr-defined]
  126. tenant_id,
  127. )
  128. )
  129. current_time = batch_end
  130. # wait for all threads to finish
  131. for future in futures:
  132. future.result()
  133. @classmethod
  134. def extract_installed_plugin_ids(cls, tenant_id: str) -> Sequence[str]:
  135. """
  136. Extract installed plugin ids.
  137. """
  138. tools = cls.extract_tool_tables(tenant_id)
  139. models = cls.extract_model_tables(tenant_id)
  140. workflows = cls.extract_workflow_tables(tenant_id)
  141. apps = cls.extract_app_tables(tenant_id)
  142. return list({*tools, *models, *workflows, *apps})
  143. @classmethod
  144. def extract_model_tables(cls, tenant_id: str) -> Sequence[str]:
  145. """
  146. Extract model tables.
  147. """
  148. models: list[str] = []
  149. table_pairs = [
  150. ("providers", "provider_name"),
  151. ("provider_models", "provider_name"),
  152. ("provider_orders", "provider_name"),
  153. ("tenant_default_models", "provider_name"),
  154. ("tenant_preferred_model_providers", "provider_name"),
  155. ("provider_model_settings", "provider_name"),
  156. ("load_balancing_model_configs", "provider_name"),
  157. ]
  158. for table, column in table_pairs:
  159. models.extend(cls.extract_model_table(tenant_id, table, column))
  160. # duplicate models
  161. models = list(set(models))
  162. return models
  163. @classmethod
  164. def extract_model_table(cls, tenant_id: str, table: str, column: str) -> Sequence[str]:
  165. """
  166. Extract model table.
  167. """
  168. with Session(db.engine) as session:
  169. rs = session.execute(
  170. sa.text(f"SELECT DISTINCT {column} FROM {table} WHERE tenant_id = :tenant_id"), {"tenant_id": tenant_id}
  171. )
  172. result = []
  173. for row in rs:
  174. provider_name = str(row[0])
  175. result.append(ModelProviderID(provider_name).plugin_id)
  176. return result
  177. @classmethod
  178. def extract_tool_tables(cls, tenant_id: str) -> Sequence[str]:
  179. """
  180. Extract tool tables.
  181. """
  182. with Session(db.engine) as session:
  183. rs = session.query(BuiltinToolProvider).where(BuiltinToolProvider.tenant_id == tenant_id).all()
  184. result = []
  185. for row in rs:
  186. result.append(ToolProviderID(row.provider).plugin_id)
  187. return result
  188. @classmethod
  189. def extract_workflow_tables(cls, tenant_id: str) -> Sequence[str]:
  190. """
  191. Extract workflow tables, only ToolNode is required.
  192. """
  193. with Session(db.engine) as session:
  194. rs = session.query(Workflow).where(Workflow.tenant_id == tenant_id).all()
  195. result = []
  196. for row in rs:
  197. graph = row.graph_dict
  198. # get nodes
  199. nodes = graph.get("nodes", [])
  200. for node in nodes:
  201. data = node.get("data", {})
  202. if data.get("type") == "tool":
  203. provider_name = data.get("provider_name")
  204. provider_type = data.get("provider_type")
  205. if provider_name not in excluded_providers and provider_type == ToolProviderType.BUILT_IN.value:
  206. result.append(ToolProviderID(provider_name).plugin_id)
  207. return result
  208. @classmethod
  209. def extract_app_tables(cls, tenant_id: str) -> Sequence[str]:
  210. """
  211. Extract app tables.
  212. """
  213. with Session(db.engine) as session:
  214. apps = session.query(App).where(App.tenant_id == tenant_id).all()
  215. if not apps:
  216. return []
  217. agent_app_model_config_ids = [
  218. app.app_model_config_id for app in apps if app.is_agent or app.mode == AppMode.AGENT_CHAT.value
  219. ]
  220. rs = session.query(AppModelConfig).where(AppModelConfig.id.in_(agent_app_model_config_ids)).all()
  221. result = []
  222. for row in rs:
  223. agent_config = row.agent_mode_dict
  224. if "tools" in agent_config and isinstance(agent_config["tools"], list):
  225. for tool in agent_config["tools"]:
  226. if isinstance(tool, dict):
  227. try:
  228. tool_entity = AgentToolEntity(**tool)
  229. if (
  230. tool_entity.provider_type == ToolProviderType.BUILT_IN.value
  231. and tool_entity.provider_id not in excluded_providers
  232. ):
  233. result.append(ToolProviderID(tool_entity.provider_id).plugin_id)
  234. except Exception:
  235. logger.exception("Failed to process tool %s", tool)
  236. continue
  237. return result
  238. @classmethod
  239. def _fetch_plugin_unique_identifier(cls, plugin_id: str) -> Optional[str]:
  240. """
  241. Fetch plugin unique identifier using plugin id.
  242. """
  243. plugin_manifest = marketplace.batch_fetch_plugin_manifests([plugin_id])
  244. if not plugin_manifest:
  245. return None
  246. return plugin_manifest[0].latest_package_identifier
  247. @classmethod
  248. def extract_unique_plugins_to_file(cls, extracted_plugins: str, output_file: str) -> None:
  249. """
  250. Extract unique plugins.
  251. """
  252. Path(output_file).write_text(json.dumps(cls.extract_unique_plugins(extracted_plugins)))
  253. @classmethod
  254. def extract_unique_plugins(cls, extracted_plugins: str) -> Mapping[str, Any]:
  255. plugins: dict[str, str] = {}
  256. plugin_ids = []
  257. plugin_not_exist = []
  258. logger.info("Extracting unique plugins from %s", extracted_plugins)
  259. with open(extracted_plugins) as f:
  260. for line in f:
  261. data = json.loads(line)
  262. new_plugin_ids = data.get("plugins", [])
  263. for plugin_id in new_plugin_ids:
  264. if plugin_id not in plugin_ids:
  265. plugin_ids.append(plugin_id)
  266. def fetch_plugin(plugin_id):
  267. try:
  268. unique_identifier = cls._fetch_plugin_unique_identifier(plugin_id)
  269. if unique_identifier:
  270. plugins[plugin_id] = unique_identifier
  271. else:
  272. plugin_not_exist.append(plugin_id)
  273. except Exception:
  274. logger.exception("Failed to fetch plugin unique identifier for %s", plugin_id)
  275. plugin_not_exist.append(plugin_id)
  276. with ThreadPoolExecutor(max_workers=10) as executor:
  277. list(tqdm.tqdm(executor.map(fetch_plugin, plugin_ids), total=len(plugin_ids)))
  278. return {"plugins": plugins, "plugin_not_exist": plugin_not_exist}
  279. @classmethod
  280. def install_plugins(cls, extracted_plugins: str, output_file: str, workers: int = 100) -> None:
  281. """
  282. Install plugins.
  283. """
  284. manager = PluginInstaller()
  285. plugins = cls.extract_unique_plugins(extracted_plugins)
  286. not_installed = []
  287. plugin_install_failed = []
  288. # use a fake tenant id to install all the plugins
  289. fake_tenant_id = uuid4().hex
  290. logger.info("Installing %s plugin instances for fake tenant %s", len(plugins["plugins"]), fake_tenant_id)
  291. thread_pool = ThreadPoolExecutor(max_workers=workers)
  292. response = cls.handle_plugin_instance_install(fake_tenant_id, plugins["plugins"])
  293. if response.get("failed"):
  294. plugin_install_failed.extend(response.get("failed", []))
  295. def install(tenant_id: str, plugin_ids: list[str]) -> None:
  296. logger.info("Installing %s plugins for tenant %s", len(plugin_ids), tenant_id)
  297. # fetch plugin already installed
  298. installed_plugins = manager.list_plugins(tenant_id)
  299. installed_plugins_ids = [plugin.plugin_id for plugin in installed_plugins]
  300. # at most 64 plugins one batch
  301. for i in range(0, len(plugin_ids), 64):
  302. batch_plugin_ids = plugin_ids[i : i + 64]
  303. batch_plugin_identifiers = [
  304. plugins["plugins"][plugin_id]
  305. for plugin_id in batch_plugin_ids
  306. if plugin_id not in installed_plugins_ids and plugin_id in plugins["plugins"]
  307. ]
  308. manager.install_from_identifiers(
  309. tenant_id,
  310. batch_plugin_identifiers,
  311. PluginInstallationSource.Marketplace,
  312. metas=[
  313. {
  314. "plugin_unique_identifier": identifier,
  315. }
  316. for identifier in batch_plugin_identifiers
  317. ],
  318. )
  319. with open(extracted_plugins) as f:
  320. """
  321. Read line by line, and install plugins for each tenant.
  322. """
  323. for line in f:
  324. data = json.loads(line)
  325. tenant_id = data.get("tenant_id")
  326. plugin_ids = data.get("plugins", [])
  327. current_not_installed = {
  328. "tenant_id": tenant_id,
  329. "plugin_not_exist": [],
  330. }
  331. # get plugin unique identifier
  332. for plugin_id in plugin_ids:
  333. unique_identifier = plugins.get(plugin_id)
  334. if unique_identifier:
  335. current_not_installed["plugin_not_exist"].append(plugin_id)
  336. if current_not_installed["plugin_not_exist"]:
  337. not_installed.append(current_not_installed)
  338. thread_pool.submit(install, tenant_id, plugin_ids)
  339. thread_pool.shutdown(wait=True)
  340. logger.info("Uninstall plugins")
  341. # get installation
  342. try:
  343. installation = manager.list_plugins(fake_tenant_id)
  344. while installation:
  345. for plugin in installation:
  346. manager.uninstall(fake_tenant_id, plugin.installation_id)
  347. installation = manager.list_plugins(fake_tenant_id)
  348. except Exception:
  349. logger.exception("Failed to get installation for tenant %s", fake_tenant_id)
  350. Path(output_file).write_text(
  351. json.dumps(
  352. {
  353. "not_installed": not_installed,
  354. "plugin_install_failed": plugin_install_failed,
  355. }
  356. )
  357. )
  358. @classmethod
  359. def handle_plugin_instance_install(
  360. cls, tenant_id: str, plugin_identifiers_map: Mapping[str, str]
  361. ) -> Mapping[str, Any]:
  362. """
  363. Install plugins for a tenant.
  364. """
  365. manager = PluginInstaller()
  366. # download all the plugins and upload
  367. thread_pool = ThreadPoolExecutor(max_workers=10)
  368. futures = []
  369. for plugin_id, plugin_identifier in plugin_identifiers_map.items():
  370. def download_and_upload(tenant_id, plugin_id, plugin_identifier):
  371. plugin_package = marketplace.download_plugin_pkg(plugin_identifier)
  372. if not plugin_package:
  373. raise Exception(f"Failed to download plugin {plugin_identifier}")
  374. # upload
  375. manager.upload_pkg(tenant_id, plugin_package, verify_signature=True)
  376. futures.append(thread_pool.submit(download_and_upload, tenant_id, plugin_id, plugin_identifier))
  377. # Wait for all downloads to complete
  378. for future in futures:
  379. future.result() # This will raise any exceptions that occurred
  380. thread_pool.shutdown(wait=True)
  381. success = []
  382. failed = []
  383. reverse_map = {v: k for k, v in plugin_identifiers_map.items()}
  384. # at most 8 plugins one batch
  385. for i in range(0, len(plugin_identifiers_map), 8):
  386. batch_plugin_ids = list(plugin_identifiers_map.keys())[i : i + 8]
  387. batch_plugin_identifiers = [plugin_identifiers_map[plugin_id] for plugin_id in batch_plugin_ids]
  388. try:
  389. response = manager.install_from_identifiers(
  390. tenant_id=tenant_id,
  391. identifiers=batch_plugin_identifiers,
  392. source=PluginInstallationSource.Marketplace,
  393. metas=[
  394. {
  395. "plugin_unique_identifier": identifier,
  396. }
  397. for identifier in batch_plugin_identifiers
  398. ],
  399. )
  400. except Exception:
  401. # add to failed
  402. failed.extend(batch_plugin_identifiers)
  403. continue
  404. if response.all_installed:
  405. success.extend(batch_plugin_identifiers)
  406. continue
  407. task_id = response.task_id
  408. done = False
  409. while not done:
  410. status = manager.fetch_plugin_installation_task(tenant_id, task_id)
  411. if status.status in [PluginInstallTaskStatus.Failed, PluginInstallTaskStatus.Success]:
  412. for plugin in status.plugins:
  413. if plugin.status == PluginInstallTaskStatus.Success:
  414. success.append(reverse_map[plugin.plugin_unique_identifier])
  415. else:
  416. failed.append(reverse_map[plugin.plugin_unique_identifier])
  417. logger.error(
  418. "Failed to install plugin %s, error: %s",
  419. plugin.plugin_unique_identifier,
  420. plugin.message,
  421. )
  422. done = True
  423. else:
  424. time.sleep(1)
  425. return {"success": success, "failed": failed}