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 23KB

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