您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

commands.py 66KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. from typing import Any, Optional
  6. import click
  7. import sqlalchemy as sa
  8. from flask import current_app
  9. from pydantic import TypeAdapter
  10. from sqlalchemy import select
  11. from sqlalchemy.exc import SQLAlchemyError
  12. from configs import dify_config
  13. from constants.languages import languages
  14. from core.helper import encrypter
  15. from core.plugin.entities.plugin import PluginInstallationSource
  16. from core.plugin.impl.plugin import PluginInstaller
  17. from core.rag.datasource.vdb.vector_factory import Vector
  18. from core.rag.datasource.vdb.vector_type import VectorType
  19. from core.rag.index_processor.constant.built_in_field import BuiltInField
  20. from core.rag.models.document import Document
  21. from core.tools.entities.tool_entities import CredentialType
  22. from core.tools.utils.system_oauth_encryption import encrypt_system_oauth_params
  23. from events.app_event import app_was_created
  24. from extensions.ext_database import db
  25. from extensions.ext_redis import redis_client
  26. from extensions.ext_storage import storage
  27. from libs.helper import email as email_validate
  28. from libs.password import hash_password, password_pattern, valid_password
  29. from libs.rsa import generate_key_pair
  30. from models import Tenant
  31. from models.dataset import Dataset, DatasetCollectionBinding, DatasetMetadata, DatasetMetadataBinding, DocumentSegment
  32. from models.dataset import Document as DatasetDocument
  33. from models.model import Account, App, AppAnnotationSetting, AppMode, Conversation, MessageAnnotation
  34. from models.oauth import DatasourceOauthParamConfig, DatasourceProvider
  35. from models.provider import Provider, ProviderModel
  36. from models.provider_ids import DatasourceProviderID, ToolProviderID
  37. from models.source import DataSourceApiKeyAuthBinding, DataSourceOauthBinding
  38. from models.tools import ToolOAuthSystemClient
  39. from services.account_service import AccountService, RegisterService, TenantService
  40. from services.clear_free_plan_tenant_expired_logs import ClearFreePlanTenantExpiredLogs
  41. from services.plugin.data_migration import PluginDataMigration
  42. from services.plugin.plugin_migration import PluginMigration
  43. from services.plugin.plugin_service import PluginService
  44. from tasks.remove_app_and_related_data_task import delete_draft_variables_batch
  45. logger = logging.getLogger(__name__)
  46. @click.command("reset-password", help="Reset the account password.")
  47. @click.option("--email", prompt=True, help="Account email to reset password for")
  48. @click.option("--new-password", prompt=True, help="New password")
  49. @click.option("--password-confirm", prompt=True, help="Confirm new password")
  50. def reset_password(email, new_password, password_confirm):
  51. """
  52. Reset password of owner account
  53. Only available in SELF_HOSTED mode
  54. """
  55. if str(new_password).strip() != str(password_confirm).strip():
  56. click.echo(click.style("Passwords do not match.", fg="red"))
  57. return
  58. account = db.session.query(Account).where(Account.email == email).one_or_none()
  59. if not account:
  60. click.echo(click.style(f"Account not found for email: {email}", fg="red"))
  61. return
  62. try:
  63. valid_password(new_password)
  64. except:
  65. click.echo(click.style(f"Invalid password. Must match {password_pattern}", fg="red"))
  66. return
  67. # generate password salt
  68. salt = secrets.token_bytes(16)
  69. base64_salt = base64.b64encode(salt).decode()
  70. # encrypt password with salt
  71. password_hashed = hash_password(new_password, salt)
  72. base64_password_hashed = base64.b64encode(password_hashed).decode()
  73. account.password = base64_password_hashed
  74. account.password_salt = base64_salt
  75. db.session.commit()
  76. AccountService.reset_login_error_rate_limit(email)
  77. click.echo(click.style("Password reset successfully.", fg="green"))
  78. @click.command("reset-email", help="Reset the account email.")
  79. @click.option("--email", prompt=True, help="Current account email")
  80. @click.option("--new-email", prompt=True, help="New email")
  81. @click.option("--email-confirm", prompt=True, help="Confirm new email")
  82. def reset_email(email, new_email, email_confirm):
  83. """
  84. Replace account email
  85. :return:
  86. """
  87. if str(new_email).strip() != str(email_confirm).strip():
  88. click.echo(click.style("New emails do not match.", fg="red"))
  89. return
  90. account = db.session.query(Account).where(Account.email == email).one_or_none()
  91. if not account:
  92. click.echo(click.style(f"Account not found for email: {email}", fg="red"))
  93. return
  94. try:
  95. email_validate(new_email)
  96. except:
  97. click.echo(click.style(f"Invalid email: {new_email}", fg="red"))
  98. return
  99. account.email = new_email
  100. db.session.commit()
  101. click.echo(click.style("Email updated successfully.", fg="green"))
  102. @click.command(
  103. "reset-encrypt-key-pair",
  104. help="Reset the asymmetric key pair of workspace for encrypt LLM credentials. "
  105. "After the reset, all LLM credentials will become invalid, "
  106. "requiring re-entry."
  107. "Only support SELF_HOSTED mode.",
  108. )
  109. @click.confirmation_option(
  110. prompt=click.style(
  111. "Are you sure you want to reset encrypt key pair? This operation cannot be rolled back!", fg="red"
  112. )
  113. )
  114. def reset_encrypt_key_pair():
  115. """
  116. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  117. After the reset, all LLM credentials will become invalid, requiring re-entry.
  118. Only support SELF_HOSTED mode.
  119. """
  120. if dify_config.EDITION != "SELF_HOSTED":
  121. click.echo(click.style("This command is only for SELF_HOSTED installations.", fg="red"))
  122. return
  123. tenants = db.session.query(Tenant).all()
  124. for tenant in tenants:
  125. if not tenant:
  126. click.echo(click.style("No workspaces found. Run /install first.", fg="red"))
  127. return
  128. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  129. db.session.query(Provider).where(Provider.provider_type == "custom", Provider.tenant_id == tenant.id).delete()
  130. db.session.query(ProviderModel).where(ProviderModel.tenant_id == tenant.id).delete()
  131. db.session.commit()
  132. click.echo(
  133. click.style(
  134. f"Congratulations! The asymmetric key pair of workspace {tenant.id} has been reset.",
  135. fg="green",
  136. )
  137. )
  138. @click.command("vdb-migrate", help="Migrate vector db.")
  139. @click.option("--scope", default="all", prompt=False, help="The scope of vector database to migrate, Default is All.")
  140. def vdb_migrate(scope: str):
  141. if scope in {"knowledge", "all"}:
  142. migrate_knowledge_vector_database()
  143. if scope in {"annotation", "all"}:
  144. migrate_annotation_vector_database()
  145. def migrate_annotation_vector_database():
  146. """
  147. Migrate annotation datas to target vector database .
  148. """
  149. click.echo(click.style("Starting annotation data migration.", fg="green"))
  150. create_count = 0
  151. skipped_count = 0
  152. total_count = 0
  153. page = 1
  154. while True:
  155. try:
  156. # get apps info
  157. per_page = 50
  158. apps = (
  159. db.session.query(App)
  160. .where(App.status == "normal")
  161. .order_by(App.created_at.desc())
  162. .limit(per_page)
  163. .offset((page - 1) * per_page)
  164. .all()
  165. )
  166. if not apps:
  167. break
  168. except SQLAlchemyError:
  169. raise
  170. page += 1
  171. for app in apps:
  172. total_count = total_count + 1
  173. click.echo(
  174. f"Processing the {total_count} app {app.id}. " + f"{create_count} created, {skipped_count} skipped."
  175. )
  176. try:
  177. click.echo(f"Creating app annotation index: {app.id}")
  178. app_annotation_setting = (
  179. db.session.query(AppAnnotationSetting).where(AppAnnotationSetting.app_id == app.id).first()
  180. )
  181. if not app_annotation_setting:
  182. skipped_count = skipped_count + 1
  183. click.echo(f"App annotation setting disabled: {app.id}")
  184. continue
  185. # get dataset_collection_binding info
  186. dataset_collection_binding = (
  187. db.session.query(DatasetCollectionBinding)
  188. .where(DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id)
  189. .first()
  190. )
  191. if not dataset_collection_binding:
  192. click.echo(f"App annotation collection binding not found: {app.id}")
  193. continue
  194. annotations = db.session.query(MessageAnnotation).where(MessageAnnotation.app_id == app.id).all()
  195. dataset = Dataset(
  196. id=app.id,
  197. tenant_id=app.tenant_id,
  198. indexing_technique="high_quality",
  199. embedding_model_provider=dataset_collection_binding.provider_name,
  200. embedding_model=dataset_collection_binding.model_name,
  201. collection_binding_id=dataset_collection_binding.id,
  202. )
  203. documents = []
  204. if annotations:
  205. for annotation in annotations:
  206. document = Document(
  207. page_content=annotation.question,
  208. metadata={"annotation_id": annotation.id, "app_id": app.id, "doc_id": annotation.id},
  209. )
  210. documents.append(document)
  211. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  212. click.echo(f"Migrating annotations for app: {app.id}.")
  213. try:
  214. vector.delete()
  215. click.echo(click.style(f"Deleted vector index for app {app.id}.", fg="green"))
  216. except Exception as e:
  217. click.echo(click.style(f"Failed to delete vector index for app {app.id}.", fg="red"))
  218. raise e
  219. if documents:
  220. try:
  221. click.echo(
  222. click.style(
  223. f"Creating vector index with {len(documents)} annotations for app {app.id}.",
  224. fg="green",
  225. )
  226. )
  227. vector.create(documents)
  228. click.echo(click.style(f"Created vector index for app {app.id}.", fg="green"))
  229. except Exception as e:
  230. click.echo(click.style(f"Failed to created vector index for app {app.id}.", fg="red"))
  231. raise e
  232. click.echo(f"Successfully migrated app annotation {app.id}.")
  233. create_count += 1
  234. except Exception as e:
  235. click.echo(
  236. click.style(f"Error creating app annotation index: {e.__class__.__name__} {str(e)}", fg="red")
  237. )
  238. continue
  239. click.echo(
  240. click.style(
  241. f"Migration complete. Created {create_count} app annotation indexes. Skipped {skipped_count} apps.",
  242. fg="green",
  243. )
  244. )
  245. def migrate_knowledge_vector_database():
  246. """
  247. Migrate vector database datas to target vector database .
  248. """
  249. click.echo(click.style("Starting vector database migration.", fg="green"))
  250. create_count = 0
  251. skipped_count = 0
  252. total_count = 0
  253. vector_type = dify_config.VECTOR_STORE
  254. upper_collection_vector_types = {
  255. VectorType.MILVUS,
  256. VectorType.PGVECTOR,
  257. VectorType.VASTBASE,
  258. VectorType.RELYT,
  259. VectorType.WEAVIATE,
  260. VectorType.ORACLE,
  261. VectorType.ELASTICSEARCH,
  262. VectorType.OPENGAUSS,
  263. VectorType.TABLESTORE,
  264. VectorType.MATRIXONE,
  265. }
  266. lower_collection_vector_types = {
  267. VectorType.ANALYTICDB,
  268. VectorType.CHROMA,
  269. VectorType.MYSCALE,
  270. VectorType.PGVECTO_RS,
  271. VectorType.TIDB_VECTOR,
  272. VectorType.OPENSEARCH,
  273. VectorType.TENCENT,
  274. VectorType.BAIDU,
  275. VectorType.VIKINGDB,
  276. VectorType.UPSTASH,
  277. VectorType.COUCHBASE,
  278. VectorType.OCEANBASE,
  279. }
  280. page = 1
  281. while True:
  282. try:
  283. stmt = (
  284. select(Dataset).where(Dataset.indexing_technique == "high_quality").order_by(Dataset.created_at.desc())
  285. )
  286. datasets = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  287. except SQLAlchemyError:
  288. raise
  289. page += 1
  290. for dataset in datasets:
  291. total_count = total_count + 1
  292. click.echo(
  293. f"Processing the {total_count} dataset {dataset.id}. {create_count} created, {skipped_count} skipped."
  294. )
  295. try:
  296. click.echo(f"Creating dataset vector database index: {dataset.id}")
  297. if dataset.index_struct_dict:
  298. if dataset.index_struct_dict["type"] == vector_type:
  299. skipped_count = skipped_count + 1
  300. continue
  301. collection_name = ""
  302. dataset_id = dataset.id
  303. if vector_type in upper_collection_vector_types:
  304. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  305. elif vector_type == VectorType.QDRANT:
  306. if dataset.collection_binding_id:
  307. dataset_collection_binding = (
  308. db.session.query(DatasetCollectionBinding)
  309. .where(DatasetCollectionBinding.id == dataset.collection_binding_id)
  310. .one_or_none()
  311. )
  312. if dataset_collection_binding:
  313. collection_name = dataset_collection_binding.collection_name
  314. else:
  315. raise ValueError("Dataset Collection Binding not found")
  316. else:
  317. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  318. elif vector_type in lower_collection_vector_types:
  319. collection_name = Dataset.gen_collection_name_by_id(dataset_id).lower()
  320. else:
  321. raise ValueError(f"Vector store {vector_type} is not supported.")
  322. index_struct_dict = {"type": vector_type, "vector_store": {"class_prefix": collection_name}}
  323. dataset.index_struct = json.dumps(index_struct_dict)
  324. vector = Vector(dataset)
  325. click.echo(f"Migrating dataset {dataset.id}.")
  326. try:
  327. vector.delete()
  328. click.echo(
  329. click.style(f"Deleted vector index {collection_name} for dataset {dataset.id}.", fg="green")
  330. )
  331. except Exception as e:
  332. click.echo(
  333. click.style(
  334. f"Failed to delete vector index {collection_name} for dataset {dataset.id}.", fg="red"
  335. )
  336. )
  337. raise e
  338. dataset_documents = (
  339. db.session.query(DatasetDocument)
  340. .where(
  341. DatasetDocument.dataset_id == dataset.id,
  342. DatasetDocument.indexing_status == "completed",
  343. DatasetDocument.enabled == True,
  344. DatasetDocument.archived == False,
  345. )
  346. .all()
  347. )
  348. documents = []
  349. segments_count = 0
  350. for dataset_document in dataset_documents:
  351. segments = (
  352. db.session.query(DocumentSegment)
  353. .where(
  354. DocumentSegment.document_id == dataset_document.id,
  355. DocumentSegment.status == "completed",
  356. DocumentSegment.enabled == True,
  357. )
  358. .all()
  359. )
  360. for segment in segments:
  361. document = Document(
  362. page_content=segment.content,
  363. metadata={
  364. "doc_id": segment.index_node_id,
  365. "doc_hash": segment.index_node_hash,
  366. "document_id": segment.document_id,
  367. "dataset_id": segment.dataset_id,
  368. },
  369. )
  370. documents.append(document)
  371. segments_count = segments_count + 1
  372. if documents:
  373. try:
  374. click.echo(
  375. click.style(
  376. f"Creating vector index with {len(documents)} documents of {segments_count}"
  377. f" segments for dataset {dataset.id}.",
  378. fg="green",
  379. )
  380. )
  381. vector.create(documents)
  382. click.echo(click.style(f"Created vector index for dataset {dataset.id}.", fg="green"))
  383. except Exception as e:
  384. click.echo(click.style(f"Failed to created vector index for dataset {dataset.id}.", fg="red"))
  385. raise e
  386. db.session.add(dataset)
  387. db.session.commit()
  388. click.echo(f"Successfully migrated dataset {dataset.id}.")
  389. create_count += 1
  390. except Exception as e:
  391. db.session.rollback()
  392. click.echo(click.style(f"Error creating dataset index: {e.__class__.__name__} {str(e)}", fg="red"))
  393. continue
  394. click.echo(
  395. click.style(
  396. f"Migration complete. Created {create_count} dataset indexes. Skipped {skipped_count} datasets.", fg="green"
  397. )
  398. )
  399. @click.command("convert-to-agent-apps", help="Convert Agent Assistant to Agent App.")
  400. def convert_to_agent_apps():
  401. """
  402. Convert Agent Assistant to Agent App.
  403. """
  404. click.echo(click.style("Starting convert to agent apps.", fg="green"))
  405. proceeded_app_ids = []
  406. while True:
  407. # fetch first 1000 apps
  408. sql_query = """SELECT a.id AS id FROM apps a
  409. INNER JOIN app_model_configs am ON a.app_model_config_id=am.id
  410. WHERE a.mode = 'chat'
  411. AND am.agent_mode is not null
  412. AND (
  413. am.agent_mode like '%"strategy": "function_call"%'
  414. OR am.agent_mode like '%"strategy": "react"%'
  415. )
  416. AND (
  417. am.agent_mode like '{"enabled": true%'
  418. OR am.agent_mode like '{"max_iteration": %'
  419. ) ORDER BY a.created_at DESC LIMIT 1000
  420. """
  421. with db.engine.begin() as conn:
  422. rs = conn.execute(sa.text(sql_query))
  423. apps = []
  424. for i in rs:
  425. app_id = str(i.id)
  426. if app_id not in proceeded_app_ids:
  427. proceeded_app_ids.append(app_id)
  428. app = db.session.query(App).where(App.id == app_id).first()
  429. if app is not None:
  430. apps.append(app)
  431. if len(apps) == 0:
  432. break
  433. for app in apps:
  434. click.echo(f"Converting app: {app.id}")
  435. try:
  436. app.mode = AppMode.AGENT_CHAT.value
  437. db.session.commit()
  438. # update conversation mode to agent
  439. db.session.query(Conversation).where(Conversation.app_id == app.id).update(
  440. {Conversation.mode: AppMode.AGENT_CHAT.value}
  441. )
  442. db.session.commit()
  443. click.echo(click.style(f"Converted app: {app.id}", fg="green"))
  444. except Exception as e:
  445. click.echo(click.style(f"Convert app error: {e.__class__.__name__} {str(e)}", fg="red"))
  446. click.echo(click.style(f"Conversion complete. Converted {len(proceeded_app_ids)} agent apps.", fg="green"))
  447. @click.command("add-qdrant-index", help="Add Qdrant index.")
  448. @click.option("--field", default="metadata.doc_id", prompt=False, help="Index field , default is metadata.doc_id.")
  449. def add_qdrant_index(field: str):
  450. click.echo(click.style("Starting Qdrant index creation.", fg="green"))
  451. create_count = 0
  452. try:
  453. bindings = db.session.query(DatasetCollectionBinding).all()
  454. if not bindings:
  455. click.echo(click.style("No dataset collection bindings found.", fg="red"))
  456. return
  457. import qdrant_client
  458. from qdrant_client.http.exceptions import UnexpectedResponse
  459. from qdrant_client.http.models import PayloadSchemaType
  460. from core.rag.datasource.vdb.qdrant.qdrant_vector import QdrantConfig
  461. for binding in bindings:
  462. if dify_config.QDRANT_URL is None:
  463. raise ValueError("Qdrant URL is required.")
  464. qdrant_config = QdrantConfig(
  465. endpoint=dify_config.QDRANT_URL,
  466. api_key=dify_config.QDRANT_API_KEY,
  467. root_path=current_app.root_path,
  468. timeout=dify_config.QDRANT_CLIENT_TIMEOUT,
  469. grpc_port=dify_config.QDRANT_GRPC_PORT,
  470. prefer_grpc=dify_config.QDRANT_GRPC_ENABLED,
  471. )
  472. try:
  473. client = qdrant_client.QdrantClient(**qdrant_config.to_qdrant_params())
  474. # create payload index
  475. client.create_payload_index(binding.collection_name, field, field_schema=PayloadSchemaType.KEYWORD)
  476. create_count += 1
  477. except UnexpectedResponse as e:
  478. # Collection does not exist, so return
  479. if e.status_code == 404:
  480. click.echo(click.style(f"Collection not found: {binding.collection_name}.", fg="red"))
  481. continue
  482. # Some other error occurred, so re-raise the exception
  483. else:
  484. click.echo(
  485. click.style(
  486. f"Failed to create Qdrant index for collection: {binding.collection_name}.", fg="red"
  487. )
  488. )
  489. except Exception:
  490. click.echo(click.style("Failed to create Qdrant client.", fg="red"))
  491. click.echo(click.style(f"Index creation complete. Created {create_count} collection indexes.", fg="green"))
  492. @click.command("old-metadata-migration", help="Old metadata migration.")
  493. def old_metadata_migration():
  494. """
  495. Old metadata migration.
  496. """
  497. click.echo(click.style("Starting old metadata migration.", fg="green"))
  498. page = 1
  499. while True:
  500. try:
  501. stmt = (
  502. select(DatasetDocument)
  503. .where(DatasetDocument.doc_metadata.is_not(None))
  504. .order_by(DatasetDocument.created_at.desc())
  505. )
  506. documents = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  507. except SQLAlchemyError:
  508. raise
  509. if not documents:
  510. break
  511. for document in documents:
  512. if document.doc_metadata:
  513. doc_metadata = document.doc_metadata
  514. for key in doc_metadata:
  515. for field in BuiltInField:
  516. if field.value == key:
  517. break
  518. else:
  519. dataset_metadata = (
  520. db.session.query(DatasetMetadata)
  521. .where(DatasetMetadata.dataset_id == document.dataset_id, DatasetMetadata.name == key)
  522. .first()
  523. )
  524. if not dataset_metadata:
  525. dataset_metadata = DatasetMetadata(
  526. tenant_id=document.tenant_id,
  527. dataset_id=document.dataset_id,
  528. name=key,
  529. type="string",
  530. created_by=document.created_by,
  531. )
  532. db.session.add(dataset_metadata)
  533. db.session.flush()
  534. dataset_metadata_binding = DatasetMetadataBinding(
  535. tenant_id=document.tenant_id,
  536. dataset_id=document.dataset_id,
  537. metadata_id=dataset_metadata.id,
  538. document_id=document.id,
  539. created_by=document.created_by,
  540. )
  541. db.session.add(dataset_metadata_binding)
  542. else:
  543. dataset_metadata_binding = (
  544. db.session.query(DatasetMetadataBinding) # type: ignore
  545. .where(
  546. DatasetMetadataBinding.dataset_id == document.dataset_id,
  547. DatasetMetadataBinding.document_id == document.id,
  548. DatasetMetadataBinding.metadata_id == dataset_metadata.id,
  549. )
  550. .first()
  551. )
  552. if not dataset_metadata_binding:
  553. dataset_metadata_binding = DatasetMetadataBinding(
  554. tenant_id=document.tenant_id,
  555. dataset_id=document.dataset_id,
  556. metadata_id=dataset_metadata.id,
  557. document_id=document.id,
  558. created_by=document.created_by,
  559. )
  560. db.session.add(dataset_metadata_binding)
  561. db.session.commit()
  562. page += 1
  563. click.echo(click.style("Old metadata migration completed.", fg="green"))
  564. @click.command("create-tenant", help="Create account and tenant.")
  565. @click.option("--email", prompt=True, help="Tenant account email.")
  566. @click.option("--name", prompt=True, help="Workspace name.")
  567. @click.option("--language", prompt=True, help="Account language, default: en-US.")
  568. def create_tenant(email: str, language: Optional[str] = None, name: Optional[str] = None):
  569. """
  570. Create tenant account
  571. """
  572. if not email:
  573. click.echo(click.style("Email is required.", fg="red"))
  574. return
  575. # Create account
  576. email = email.strip()
  577. if "@" not in email:
  578. click.echo(click.style("Invalid email address.", fg="red"))
  579. return
  580. account_name = email.split("@")[0]
  581. if language not in languages:
  582. language = "en-US"
  583. # Validates name encoding for non-Latin characters.
  584. name = name.strip().encode("utf-8").decode("utf-8") if name else None
  585. # generate random password
  586. new_password = secrets.token_urlsafe(16)
  587. # register account
  588. account = RegisterService.register(
  589. email=email,
  590. name=account_name,
  591. password=new_password,
  592. language=language,
  593. create_workspace_required=False,
  594. )
  595. TenantService.create_owner_tenant_if_not_exist(account, name)
  596. click.echo(
  597. click.style(
  598. f"Account and tenant created.\nAccount: {email}\nPassword: {new_password}",
  599. fg="green",
  600. )
  601. )
  602. @click.command("upgrade-db", help="Upgrade the database")
  603. def upgrade_db():
  604. click.echo("Preparing database migration...")
  605. lock = redis_client.lock(name="db_upgrade_lock", timeout=60)
  606. if lock.acquire(blocking=False):
  607. try:
  608. click.echo(click.style("Starting database migration.", fg="green"))
  609. # run db migration
  610. import flask_migrate
  611. flask_migrate.upgrade()
  612. click.echo(click.style("Database migration successful!", fg="green"))
  613. except Exception:
  614. logger.exception("Failed to execute database migration")
  615. finally:
  616. lock.release()
  617. else:
  618. click.echo("Database migration skipped")
  619. @click.command("fix-app-site-missing", help="Fix app related site missing issue.")
  620. def fix_app_site_missing():
  621. """
  622. Fix app related site missing issue.
  623. """
  624. click.echo(click.style("Starting fix for missing app-related sites.", fg="green"))
  625. failed_app_ids = []
  626. while True:
  627. sql = """select apps.id as id from apps left join sites on sites.app_id=apps.id
  628. where sites.id is null limit 1000"""
  629. with db.engine.begin() as conn:
  630. rs = conn.execute(sa.text(sql))
  631. processed_count = 0
  632. for i in rs:
  633. processed_count += 1
  634. app_id = str(i.id)
  635. if app_id in failed_app_ids:
  636. continue
  637. try:
  638. app = db.session.query(App).where(App.id == app_id).first()
  639. if not app:
  640. print(f"App {app_id} not found")
  641. continue
  642. tenant = app.tenant
  643. if tenant:
  644. accounts = tenant.get_accounts()
  645. if not accounts:
  646. print(f"Fix failed for app {app.id}")
  647. continue
  648. account = accounts[0]
  649. print(f"Fixing missing site for app {app.id}")
  650. app_was_created.send(app, account=account)
  651. except Exception:
  652. failed_app_ids.append(app_id)
  653. click.echo(click.style(f"Failed to fix missing site for app {app_id}", fg="red"))
  654. logger.exception("Failed to fix app related site missing issue, app_id: %s", app_id)
  655. continue
  656. if not processed_count:
  657. break
  658. click.echo(click.style("Fix for missing app-related sites completed successfully!", fg="green"))
  659. @click.command("migrate-data-for-plugin", help="Migrate data for plugin.")
  660. def migrate_data_for_plugin():
  661. """
  662. Migrate data for plugin.
  663. """
  664. click.echo(click.style("Starting migrate data for plugin.", fg="white"))
  665. PluginDataMigration.migrate()
  666. click.echo(click.style("Migrate data for plugin completed.", fg="green"))
  667. @click.command("extract-plugins", help="Extract plugins.")
  668. @click.option("--output_file", prompt=True, help="The file to store the extracted plugins.", default="plugins.jsonl")
  669. @click.option("--workers", prompt=True, help="The number of workers to extract plugins.", default=10)
  670. def extract_plugins(output_file: str, workers: int):
  671. """
  672. Extract plugins.
  673. """
  674. click.echo(click.style("Starting extract plugins.", fg="white"))
  675. PluginMigration.extract_plugins(output_file, workers)
  676. click.echo(click.style("Extract plugins completed.", fg="green"))
  677. @click.command("extract-unique-identifiers", help="Extract unique identifiers.")
  678. @click.option(
  679. "--output_file",
  680. prompt=True,
  681. help="The file to store the extracted unique identifiers.",
  682. default="unique_identifiers.json",
  683. )
  684. @click.option(
  685. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  686. )
  687. def extract_unique_plugins(output_file: str, input_file: str):
  688. """
  689. Extract unique plugins.
  690. """
  691. click.echo(click.style("Starting extract unique plugins.", fg="white"))
  692. PluginMigration.extract_unique_plugins_to_file(input_file, output_file)
  693. click.echo(click.style("Extract unique plugins completed.", fg="green"))
  694. @click.command("install-plugins", help="Install plugins.")
  695. @click.option(
  696. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  697. )
  698. @click.option(
  699. "--output_file", prompt=True, help="The file to store the installed plugins.", default="installed_plugins.jsonl"
  700. )
  701. @click.option("--workers", prompt=True, help="The number of workers to install plugins.", default=100)
  702. def install_plugins(input_file: str, output_file: str, workers: int):
  703. """
  704. Install plugins.
  705. """
  706. click.echo(click.style("Starting install plugins.", fg="white"))
  707. PluginMigration.install_plugins(input_file, output_file, workers)
  708. click.echo(click.style("Install plugins completed.", fg="green"))
  709. @click.command("clear-free-plan-tenant-expired-logs", help="Clear free plan tenant expired logs.")
  710. @click.option("--days", prompt=True, help="The days to clear free plan tenant expired logs.", default=30)
  711. @click.option("--batch", prompt=True, help="The batch size to clear free plan tenant expired logs.", default=100)
  712. @click.option(
  713. "--tenant_ids",
  714. prompt=True,
  715. multiple=True,
  716. help="The tenant ids to clear free plan tenant expired logs.",
  717. )
  718. def clear_free_plan_tenant_expired_logs(days: int, batch: int, tenant_ids: list[str]):
  719. """
  720. Clear free plan tenant expired logs.
  721. """
  722. click.echo(click.style("Starting clear free plan tenant expired logs.", fg="white"))
  723. ClearFreePlanTenantExpiredLogs.process(days, batch, tenant_ids)
  724. click.echo(click.style("Clear free plan tenant expired logs completed.", fg="green"))
  725. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  726. @click.command("clear-orphaned-file-records", help="Clear orphaned file records.")
  727. def clear_orphaned_file_records(force: bool):
  728. """
  729. Clear orphaned file records in the database.
  730. """
  731. # define tables and columns to process
  732. files_tables = [
  733. {"table": "upload_files", "id_column": "id", "key_column": "key"},
  734. {"table": "tool_files", "id_column": "id", "key_column": "file_key"},
  735. ]
  736. ids_tables = [
  737. {"type": "uuid", "table": "message_files", "column": "upload_file_id"},
  738. {"type": "text", "table": "documents", "column": "data_source_info"},
  739. {"type": "text", "table": "document_segments", "column": "content"},
  740. {"type": "text", "table": "messages", "column": "answer"},
  741. {"type": "text", "table": "workflow_node_executions", "column": "inputs"},
  742. {"type": "text", "table": "workflow_node_executions", "column": "process_data"},
  743. {"type": "text", "table": "workflow_node_executions", "column": "outputs"},
  744. {"type": "text", "table": "conversations", "column": "introduction"},
  745. {"type": "text", "table": "conversations", "column": "system_instruction"},
  746. {"type": "text", "table": "accounts", "column": "avatar"},
  747. {"type": "text", "table": "apps", "column": "icon"},
  748. {"type": "text", "table": "sites", "column": "icon"},
  749. {"type": "json", "table": "messages", "column": "inputs"},
  750. {"type": "json", "table": "messages", "column": "message"},
  751. ]
  752. # notify user and ask for confirmation
  753. click.echo(
  754. click.style(
  755. "This command will first find and delete orphaned file records from the message_files table,", fg="yellow"
  756. )
  757. )
  758. click.echo(
  759. click.style(
  760. "and then it will find and delete orphaned file records in the following tables:",
  761. fg="yellow",
  762. )
  763. )
  764. for files_table in files_tables:
  765. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  766. click.echo(
  767. click.style("The following tables and columns will be scanned to find orphaned file records:", fg="yellow")
  768. )
  769. for ids_table in ids_tables:
  770. click.echo(click.style(f"- {ids_table['table']} ({ids_table['column']})", fg="yellow"))
  771. click.echo("")
  772. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  773. click.echo(
  774. click.style(
  775. (
  776. "Since not all patterns have been fully tested, "
  777. "please note that this command may delete unintended file records."
  778. ),
  779. fg="yellow",
  780. )
  781. )
  782. click.echo(
  783. click.style("This cannot be undone. Please make sure to back up your database before proceeding.", fg="yellow")
  784. )
  785. click.echo(
  786. click.style(
  787. (
  788. "It is also recommended to run this during the maintenance window, "
  789. "as this may cause high load on your instance."
  790. ),
  791. fg="yellow",
  792. )
  793. )
  794. if not force:
  795. click.confirm("Do you want to proceed?", abort=True)
  796. # start the cleanup process
  797. click.echo(click.style("Starting orphaned file records cleanup.", fg="white"))
  798. # clean up the orphaned records in the message_files table where message_id doesn't exist in messages table
  799. try:
  800. click.echo(
  801. click.style("- Listing message_files records where message_id doesn't exist in messages table", fg="white")
  802. )
  803. query = (
  804. "SELECT mf.id, mf.message_id "
  805. "FROM message_files mf LEFT JOIN messages m ON mf.message_id = m.id "
  806. "WHERE m.id IS NULL"
  807. )
  808. orphaned_message_files = []
  809. with db.engine.begin() as conn:
  810. rs = conn.execute(sa.text(query))
  811. for i in rs:
  812. orphaned_message_files.append({"id": str(i[0]), "message_id": str(i[1])})
  813. if orphaned_message_files:
  814. click.echo(click.style(f"Found {len(orphaned_message_files)} orphaned message_files records:", fg="white"))
  815. for record in orphaned_message_files:
  816. click.echo(click.style(f" - id: {record['id']}, message_id: {record['message_id']}", fg="black"))
  817. if not force:
  818. click.confirm(
  819. (
  820. f"Do you want to proceed "
  821. f"to delete all {len(orphaned_message_files)} orphaned message_files records?"
  822. ),
  823. abort=True,
  824. )
  825. click.echo(click.style("- Deleting orphaned message_files records", fg="white"))
  826. query = "DELETE FROM message_files WHERE id IN :ids"
  827. with db.engine.begin() as conn:
  828. conn.execute(sa.text(query), {"ids": tuple([record["id"] for record in orphaned_message_files])})
  829. click.echo(
  830. click.style(f"Removed {len(orphaned_message_files)} orphaned message_files records.", fg="green")
  831. )
  832. else:
  833. click.echo(click.style("No orphaned message_files records found. There is nothing to delete.", fg="green"))
  834. except Exception as e:
  835. click.echo(click.style(f"Error deleting orphaned message_files records: {str(e)}", fg="red"))
  836. # clean up the orphaned records in the rest of the *_files tables
  837. try:
  838. # fetch file id and keys from each table
  839. all_files_in_tables = []
  840. for files_table in files_tables:
  841. click.echo(click.style(f"- Listing file records in table {files_table['table']}", fg="white"))
  842. query = f"SELECT {files_table['id_column']}, {files_table['key_column']} FROM {files_table['table']}"
  843. with db.engine.begin() as conn:
  844. rs = conn.execute(sa.text(query))
  845. for i in rs:
  846. all_files_in_tables.append({"table": files_table["table"], "id": str(i[0]), "key": i[1]})
  847. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  848. # fetch referred table and columns
  849. guid_regexp = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
  850. all_ids_in_tables = []
  851. for ids_table in ids_tables:
  852. query = ""
  853. if ids_table["type"] == "uuid":
  854. click.echo(
  855. click.style(
  856. f"- Listing file ids in column {ids_table['column']} in table {ids_table['table']}", fg="white"
  857. )
  858. )
  859. query = (
  860. f"SELECT {ids_table['column']} FROM {ids_table['table']} WHERE {ids_table['column']} IS NOT NULL"
  861. )
  862. with db.engine.begin() as conn:
  863. rs = conn.execute(sa.text(query))
  864. for i in rs:
  865. all_ids_in_tables.append({"table": ids_table["table"], "id": str(i[0])})
  866. elif ids_table["type"] == "text":
  867. click.echo(
  868. click.style(
  869. f"- Listing file-id-like strings in column {ids_table['column']} in table {ids_table['table']}",
  870. fg="white",
  871. )
  872. )
  873. query = (
  874. f"SELECT regexp_matches({ids_table['column']}, '{guid_regexp}', 'g') AS extracted_id "
  875. f"FROM {ids_table['table']}"
  876. )
  877. with db.engine.begin() as conn:
  878. rs = conn.execute(sa.text(query))
  879. for i in rs:
  880. for j in i[0]:
  881. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  882. elif ids_table["type"] == "json":
  883. click.echo(
  884. click.style(
  885. (
  886. f"- Listing file-id-like JSON string in column {ids_table['column']} "
  887. f"in table {ids_table['table']}"
  888. ),
  889. fg="white",
  890. )
  891. )
  892. query = (
  893. f"SELECT regexp_matches({ids_table['column']}::text, '{guid_regexp}', 'g') AS extracted_id "
  894. f"FROM {ids_table['table']}"
  895. )
  896. with db.engine.begin() as conn:
  897. rs = conn.execute(sa.text(query))
  898. for i in rs:
  899. for j in i[0]:
  900. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  901. click.echo(click.style(f"Found {len(all_ids_in_tables)} file ids in tables.", fg="white"))
  902. except Exception as e:
  903. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  904. return
  905. # find orphaned files
  906. all_files = [file["id"] for file in all_files_in_tables]
  907. all_ids = [file["id"] for file in all_ids_in_tables]
  908. orphaned_files = list(set(all_files) - set(all_ids))
  909. if not orphaned_files:
  910. click.echo(click.style("No orphaned file records found. There is nothing to delete.", fg="green"))
  911. return
  912. click.echo(click.style(f"Found {len(orphaned_files)} orphaned file records.", fg="white"))
  913. for file in orphaned_files:
  914. click.echo(click.style(f"- orphaned file id: {file}", fg="black"))
  915. if not force:
  916. click.confirm(f"Do you want to proceed to delete all {len(orphaned_files)} orphaned file records?", abort=True)
  917. # delete orphaned records for each file
  918. try:
  919. for files_table in files_tables:
  920. click.echo(click.style(f"- Deleting orphaned file records in table {files_table['table']}", fg="white"))
  921. query = f"DELETE FROM {files_table['table']} WHERE {files_table['id_column']} IN :ids"
  922. with db.engine.begin() as conn:
  923. conn.execute(sa.text(query), {"ids": tuple(orphaned_files)})
  924. except Exception as e:
  925. click.echo(click.style(f"Error deleting orphaned file records: {str(e)}", fg="red"))
  926. return
  927. click.echo(click.style(f"Removed {len(orphaned_files)} orphaned file records.", fg="green"))
  928. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  929. @click.command("remove-orphaned-files-on-storage", help="Remove orphaned files on the storage.")
  930. def remove_orphaned_files_on_storage(force: bool):
  931. """
  932. Remove orphaned files on the storage.
  933. """
  934. # define tables and columns to process
  935. files_tables = [
  936. {"table": "upload_files", "key_column": "key"},
  937. {"table": "tool_files", "key_column": "file_key"},
  938. ]
  939. storage_paths = ["image_files", "tools", "upload_files"]
  940. # notify user and ask for confirmation
  941. click.echo(click.style("This command will find and remove orphaned files on the storage,", fg="yellow"))
  942. click.echo(
  943. click.style("by comparing the files on the storage with the records in the following tables:", fg="yellow")
  944. )
  945. for files_table in files_tables:
  946. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  947. click.echo(click.style("The following paths on the storage will be scanned to find orphaned files:", fg="yellow"))
  948. for storage_path in storage_paths:
  949. click.echo(click.style(f"- {storage_path}", fg="yellow"))
  950. click.echo("")
  951. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  952. click.echo(
  953. click.style(
  954. "Currently, this command will work only for opendal based storage (STORAGE_TYPE=opendal).", fg="yellow"
  955. )
  956. )
  957. click.echo(
  958. click.style(
  959. "Since not all patterns have been fully tested, please note that this command may delete unintended files.",
  960. fg="yellow",
  961. )
  962. )
  963. click.echo(
  964. click.style("This cannot be undone. Please make sure to back up your storage before proceeding.", fg="yellow")
  965. )
  966. click.echo(
  967. click.style(
  968. (
  969. "It is also recommended to run this during the maintenance window, "
  970. "as this may cause high load on your instance."
  971. ),
  972. fg="yellow",
  973. )
  974. )
  975. if not force:
  976. click.confirm("Do you want to proceed?", abort=True)
  977. # start the cleanup process
  978. click.echo(click.style("Starting orphaned files cleanup.", fg="white"))
  979. # fetch file id and keys from each table
  980. all_files_in_tables = []
  981. try:
  982. for files_table in files_tables:
  983. click.echo(click.style(f"- Listing files from table {files_table['table']}", fg="white"))
  984. query = f"SELECT {files_table['key_column']} FROM {files_table['table']}"
  985. with db.engine.begin() as conn:
  986. rs = conn.execute(sa.text(query))
  987. for i in rs:
  988. all_files_in_tables.append(str(i[0]))
  989. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  990. except Exception as e:
  991. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  992. all_files_on_storage = []
  993. for storage_path in storage_paths:
  994. try:
  995. click.echo(click.style(f"- Scanning files on storage path {storage_path}", fg="white"))
  996. files = storage.scan(path=storage_path, files=True, directories=False)
  997. all_files_on_storage.extend(files)
  998. except FileNotFoundError as e:
  999. click.echo(click.style(f" -> Skipping path {storage_path} as it does not exist.", fg="yellow"))
  1000. continue
  1001. except Exception as e:
  1002. click.echo(click.style(f" -> Error scanning files on storage path {storage_path}: {str(e)}", fg="red"))
  1003. continue
  1004. click.echo(click.style(f"Found {len(all_files_on_storage)} files on storage.", fg="white"))
  1005. # find orphaned files
  1006. orphaned_files = list(set(all_files_on_storage) - set(all_files_in_tables))
  1007. if not orphaned_files:
  1008. click.echo(click.style("No orphaned files found. There is nothing to remove.", fg="green"))
  1009. return
  1010. click.echo(click.style(f"Found {len(orphaned_files)} orphaned files.", fg="white"))
  1011. for file in orphaned_files:
  1012. click.echo(click.style(f"- orphaned file: {file}", fg="black"))
  1013. if not force:
  1014. click.confirm(f"Do you want to proceed to remove all {len(orphaned_files)} orphaned files?", abort=True)
  1015. # delete orphaned files
  1016. removed_files = 0
  1017. error_files = 0
  1018. for file in orphaned_files:
  1019. try:
  1020. storage.delete(file)
  1021. removed_files += 1
  1022. click.echo(click.style(f"- Removing orphaned file: {file}", fg="white"))
  1023. except Exception as e:
  1024. error_files += 1
  1025. click.echo(click.style(f"- Error deleting orphaned file {file}: {str(e)}", fg="red"))
  1026. continue
  1027. if error_files == 0:
  1028. click.echo(click.style(f"Removed {removed_files} orphaned files without errors.", fg="green"))
  1029. else:
  1030. click.echo(click.style(f"Removed {removed_files} orphaned files, with {error_files} errors.", fg="yellow"))
  1031. @click.command("setup-system-tool-oauth-client", help="Setup system tool oauth client.")
  1032. @click.option("--provider", prompt=True, help="Provider name")
  1033. @click.option("--client-params", prompt=True, help="Client Params")
  1034. def setup_system_tool_oauth_client(provider, client_params):
  1035. """
  1036. Setup system tool oauth client
  1037. """
  1038. provider_id = ToolProviderID(provider)
  1039. provider_name = provider_id.provider_name
  1040. plugin_id = provider_id.plugin_id
  1041. try:
  1042. # json validate
  1043. click.echo(click.style(f"Validating client params: {client_params}", fg="yellow"))
  1044. client_params_dict = TypeAdapter(dict[str, Any]).validate_json(client_params)
  1045. click.echo(click.style("Client params validated successfully.", fg="green"))
  1046. click.echo(click.style(f"Encrypting client params: {client_params}", fg="yellow"))
  1047. click.echo(click.style(f"Using SECRET_KEY: `{dify_config.SECRET_KEY}`", fg="yellow"))
  1048. oauth_client_params = encrypt_system_oauth_params(client_params_dict)
  1049. click.echo(click.style("Client params encrypted successfully.", fg="green"))
  1050. except Exception as e:
  1051. click.echo(click.style(f"Error parsing client params: {str(e)}", fg="red"))
  1052. return
  1053. deleted_count = (
  1054. db.session.query(ToolOAuthSystemClient)
  1055. .filter_by(
  1056. provider=provider_name,
  1057. plugin_id=plugin_id,
  1058. )
  1059. .delete()
  1060. )
  1061. if deleted_count > 0:
  1062. click.echo(click.style(f"Deleted {deleted_count} existing oauth client params.", fg="yellow"))
  1063. oauth_client = ToolOAuthSystemClient(
  1064. provider=provider_name,
  1065. plugin_id=plugin_id,
  1066. encrypted_oauth_params=oauth_client_params,
  1067. )
  1068. db.session.add(oauth_client)
  1069. db.session.commit()
  1070. click.echo(click.style(f"OAuth client params setup successfully. id: {oauth_client.id}", fg="green"))
  1071. def _find_orphaned_draft_variables(batch_size: int = 1000) -> list[str]:
  1072. """
  1073. Find draft variables that reference non-existent apps.
  1074. Args:
  1075. batch_size: Maximum number of orphaned app IDs to return
  1076. Returns:
  1077. List of app IDs that have draft variables but don't exist in the apps table
  1078. """
  1079. query = """
  1080. SELECT DISTINCT wdv.app_id
  1081. FROM workflow_draft_variables AS wdv
  1082. WHERE NOT EXISTS(
  1083. SELECT 1 FROM apps WHERE apps.id = wdv.app_id
  1084. )
  1085. LIMIT :batch_size
  1086. """
  1087. with db.engine.connect() as conn:
  1088. result = conn.execute(sa.text(query), {"batch_size": batch_size})
  1089. return [row[0] for row in result]
  1090. def _count_orphaned_draft_variables() -> dict[str, Any]:
  1091. """
  1092. Count orphaned draft variables by app, including associated file counts.
  1093. Returns:
  1094. Dictionary with statistics about orphaned variables and files
  1095. """
  1096. # Count orphaned variables by app
  1097. variables_query = """
  1098. SELECT
  1099. wdv.app_id,
  1100. COUNT(*) as variable_count,
  1101. COUNT(wdv.file_id) as file_count
  1102. FROM workflow_draft_variables AS wdv
  1103. WHERE NOT EXISTS(
  1104. SELECT 1 FROM apps WHERE apps.id = wdv.app_id
  1105. )
  1106. GROUP BY wdv.app_id
  1107. ORDER BY variable_count DESC
  1108. """
  1109. with db.engine.connect() as conn:
  1110. result = conn.execute(sa.text(variables_query))
  1111. orphaned_by_app = {}
  1112. total_files = 0
  1113. for row in result:
  1114. app_id, variable_count, file_count = row
  1115. orphaned_by_app[app_id] = {"variables": variable_count, "files": file_count}
  1116. total_files += file_count
  1117. total_orphaned = sum(app_data["variables"] for app_data in orphaned_by_app.values())
  1118. app_count = len(orphaned_by_app)
  1119. return {
  1120. "total_orphaned_variables": total_orphaned,
  1121. "total_orphaned_files": total_files,
  1122. "orphaned_app_count": app_count,
  1123. "orphaned_by_app": orphaned_by_app,
  1124. }
  1125. @click.command()
  1126. @click.option("--dry-run", is_flag=True, help="Show what would be deleted without actually deleting")
  1127. @click.option("--batch-size", default=1000, help="Number of records to process per batch (default 1000)")
  1128. @click.option("--max-apps", default=None, type=int, help="Maximum number of apps to process (default: no limit)")
  1129. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  1130. def cleanup_orphaned_draft_variables(
  1131. dry_run: bool,
  1132. batch_size: int,
  1133. max_apps: int | None,
  1134. force: bool = False,
  1135. ):
  1136. """
  1137. Clean up orphaned draft variables from the database.
  1138. This script finds and removes draft variables that belong to apps
  1139. that no longer exist in the database.
  1140. """
  1141. logger = logging.getLogger(__name__)
  1142. # Get statistics
  1143. stats = _count_orphaned_draft_variables()
  1144. logger.info("Found %s orphaned draft variables", stats["total_orphaned_variables"])
  1145. logger.info("Found %s associated offload files", stats["total_orphaned_files"])
  1146. logger.info("Across %s non-existent apps", stats["orphaned_app_count"])
  1147. if stats["total_orphaned_variables"] == 0:
  1148. logger.info("No orphaned draft variables found. Exiting.")
  1149. return
  1150. if dry_run:
  1151. logger.info("DRY RUN: Would delete the following:")
  1152. for app_id, data in sorted(stats["orphaned_by_app"].items(), key=lambda x: x[1]["variables"], reverse=True)[
  1153. :10
  1154. ]: # Show top 10
  1155. logger.info(" App %s: %s variables, %s files", app_id, data["variables"], data["files"])
  1156. if len(stats["orphaned_by_app"]) > 10:
  1157. logger.info(" ... and %s more apps", len(stats["orphaned_by_app"]) - 10)
  1158. return
  1159. # Confirm deletion
  1160. if not force:
  1161. click.confirm(
  1162. f"Are you sure you want to delete {stats['total_orphaned_variables']} "
  1163. f"orphaned draft variables and {stats['total_orphaned_files']} associated files "
  1164. f"from {stats['orphaned_app_count']} apps?",
  1165. abort=True,
  1166. )
  1167. total_deleted = 0
  1168. processed_apps = 0
  1169. while True:
  1170. if max_apps and processed_apps >= max_apps:
  1171. logger.info("Reached maximum app limit (%s). Stopping.", max_apps)
  1172. break
  1173. orphaned_app_ids = _find_orphaned_draft_variables(batch_size=10)
  1174. if not orphaned_app_ids:
  1175. logger.info("No more orphaned draft variables found.")
  1176. break
  1177. for app_id in orphaned_app_ids:
  1178. if max_apps and processed_apps >= max_apps:
  1179. break
  1180. try:
  1181. deleted_count = delete_draft_variables_batch(app_id, batch_size)
  1182. total_deleted += deleted_count
  1183. processed_apps += 1
  1184. logger.info("Deleted %s variables for app %s", deleted_count, app_id)
  1185. except Exception:
  1186. logger.exception("Error processing app %s", app_id)
  1187. continue
  1188. logger.info("Cleanup completed. Total deleted: %s variables across %s apps", total_deleted, processed_apps)
  1189. @click.command("setup-datasource-oauth-client", help="Setup datasource oauth client.")
  1190. @click.option("--provider", prompt=True, help="Provider name")
  1191. @click.option("--client-params", prompt=True, help="Client Params")
  1192. def setup_datasource_oauth_client(provider, client_params):
  1193. """
  1194. Setup datasource oauth client
  1195. """
  1196. provider_id = DatasourceProviderID(provider)
  1197. provider_name = provider_id.provider_name
  1198. plugin_id = provider_id.plugin_id
  1199. try:
  1200. # json validate
  1201. click.echo(click.style(f"Validating client params: {client_params}", fg="yellow"))
  1202. client_params_dict = TypeAdapter(dict[str, Any]).validate_json(client_params)
  1203. click.echo(click.style("Client params validated successfully.", fg="green"))
  1204. except Exception as e:
  1205. click.echo(click.style(f"Error parsing client params: {str(e)}", fg="red"))
  1206. return
  1207. click.echo(click.style(f"Ready to delete existing oauth client params: {provider_name}", fg="yellow"))
  1208. deleted_count = (
  1209. db.session.query(DatasourceOauthParamConfig)
  1210. .filter_by(
  1211. provider=provider_name,
  1212. plugin_id=plugin_id,
  1213. )
  1214. .delete()
  1215. )
  1216. if deleted_count > 0:
  1217. click.echo(click.style(f"Deleted {deleted_count} existing oauth client params.", fg="yellow"))
  1218. click.echo(click.style(f"Ready to setup datasource oauth client: {provider_name}", fg="yellow"))
  1219. oauth_client = DatasourceOauthParamConfig(
  1220. provider=provider_name,
  1221. plugin_id=plugin_id,
  1222. system_credentials=client_params_dict,
  1223. )
  1224. db.session.add(oauth_client)
  1225. db.session.commit()
  1226. click.echo(click.style(f"provider: {provider_name}", fg="green"))
  1227. click.echo(click.style(f"plugin_id: {plugin_id}", fg="green"))
  1228. click.echo(click.style(f"params: {json.dumps(client_params_dict, indent=2, ensure_ascii=False)}", fg="green"))
  1229. click.echo(click.style(f"Datasource oauth client setup successfully. id: {oauth_client.id}", fg="green"))
  1230. @click.command("transform-datasource-credentials", help="Transform datasource credentials.")
  1231. def transform_datasource_credentials():
  1232. """
  1233. Transform datasource credentials
  1234. """
  1235. try:
  1236. installer_manager = PluginInstaller()
  1237. plugin_migration = PluginMigration()
  1238. notion_plugin_id = "langgenius/notion_datasource"
  1239. firecrawl_plugin_id = "langgenius/firecrawl_datasource"
  1240. jina_plugin_id = "langgenius/jina_datasource"
  1241. notion_plugin_unique_identifier = plugin_migration._fetch_plugin_unique_identifier(notion_plugin_id)
  1242. firecrawl_plugin_unique_identifier = plugin_migration._fetch_plugin_unique_identifier(firecrawl_plugin_id)
  1243. jina_plugin_unique_identifier = plugin_migration._fetch_plugin_unique_identifier(jina_plugin_id)
  1244. oauth_credential_type = CredentialType.OAUTH2
  1245. api_key_credential_type = CredentialType.API_KEY
  1246. # deal notion credentials
  1247. deal_notion_count = 0
  1248. notion_credentials = db.session.query(DataSourceOauthBinding).filter_by(provider="notion").all()
  1249. if notion_credentials:
  1250. notion_credentials_tenant_mapping: dict[str, list[DataSourceOauthBinding]] = {}
  1251. for credential in notion_credentials:
  1252. tenant_id = credential.tenant_id
  1253. if tenant_id not in notion_credentials_tenant_mapping:
  1254. notion_credentials_tenant_mapping[tenant_id] = []
  1255. notion_credentials_tenant_mapping[tenant_id].append(credential)
  1256. for tenant_id, credentials in notion_credentials_tenant_mapping.items():
  1257. # check notion plugin is installed
  1258. installed_plugins = installer_manager.list_plugins(tenant_id)
  1259. installed_plugins_ids = [plugin.plugin_id for plugin in installed_plugins]
  1260. if notion_plugin_id not in installed_plugins_ids:
  1261. if notion_plugin_unique_identifier:
  1262. # install notion plugin
  1263. PluginService.install_from_marketplace_pkg(tenant_id, [notion_plugin_unique_identifier])
  1264. auth_count = 0
  1265. for credential in credentials:
  1266. auth_count += 1
  1267. # get credential oauth params
  1268. access_token = credential.access_token
  1269. # notion info
  1270. notion_info = credential.source_info
  1271. workspace_id = notion_info.get("workspace_id")
  1272. workspace_name = notion_info.get("workspace_name")
  1273. workspace_icon = notion_info.get("workspace_icon")
  1274. new_credentials = {
  1275. "integration_secret": encrypter.encrypt_token(tenant_id, access_token),
  1276. "workspace_id": workspace_id,
  1277. "workspace_name": workspace_name,
  1278. "workspace_icon": workspace_icon,
  1279. }
  1280. datasource_provider = DatasourceProvider(
  1281. provider="notion_datasource",
  1282. tenant_id=tenant_id,
  1283. plugin_id=notion_plugin_id,
  1284. auth_type=oauth_credential_type.value,
  1285. encrypted_credentials=new_credentials,
  1286. name=f"Auth {auth_count}",
  1287. avatar_url=workspace_icon or "default",
  1288. is_default=False,
  1289. )
  1290. db.session.add(datasource_provider)
  1291. deal_notion_count += 1
  1292. db.session.commit()
  1293. # deal firecrawl credentials
  1294. deal_firecrawl_count = 0
  1295. firecrawl_credentials = db.session.query(DataSourceApiKeyAuthBinding).filter_by(provider="firecrawl").all()
  1296. if firecrawl_credentials:
  1297. firecrawl_credentials_tenant_mapping: dict[str, list[DataSourceApiKeyAuthBinding]] = {}
  1298. for credential in firecrawl_credentials:
  1299. tenant_id = credential.tenant_id
  1300. if tenant_id not in firecrawl_credentials_tenant_mapping:
  1301. firecrawl_credentials_tenant_mapping[tenant_id] = []
  1302. firecrawl_credentials_tenant_mapping[tenant_id].append(credential)
  1303. for tenant_id, credentials in firecrawl_credentials_tenant_mapping.items():
  1304. # check firecrawl plugin is installed
  1305. installed_plugins = installer_manager.list_plugins(tenant_id)
  1306. installed_plugins_ids = [plugin.plugin_id for plugin in installed_plugins]
  1307. if firecrawl_plugin_id not in installed_plugins_ids:
  1308. if firecrawl_plugin_unique_identifier:
  1309. # install firecrawl plugin
  1310. PluginService.install_from_marketplace_pkg(tenant_id, [firecrawl_plugin_unique_identifier])
  1311. auth_count = 0
  1312. for credential in credentials:
  1313. auth_count += 1
  1314. # get credential api key
  1315. credentials_json =json.loads(credential.credentials)
  1316. api_key = credentials_json.get("config", {}).get("api_key")
  1317. base_url = credentials_json.get("config", {}).get("base_url")
  1318. new_credentials = {
  1319. "firecrawl_api_key": api_key,
  1320. "base_url": base_url,
  1321. }
  1322. datasource_provider = DatasourceProvider(
  1323. provider="firecrawl",
  1324. tenant_id=tenant_id,
  1325. plugin_id=firecrawl_plugin_id,
  1326. auth_type=api_key_credential_type.value,
  1327. encrypted_credentials=new_credentials,
  1328. name=f"Auth {auth_count}",
  1329. avatar_url="default",
  1330. is_default=False,
  1331. )
  1332. db.session.add(datasource_provider)
  1333. deal_firecrawl_count += 1
  1334. db.session.commit()
  1335. # deal jina credentials
  1336. deal_jina_count = 0
  1337. jina_credentials = db.session.query(DataSourceApiKeyAuthBinding).filter_by(provider="jinareader").all()
  1338. if jina_credentials:
  1339. jina_credentials_tenant_mapping: dict[str, list[DataSourceApiKeyAuthBinding]] = {}
  1340. for credential in jina_credentials:
  1341. tenant_id = credential.tenant_id
  1342. if tenant_id not in jina_credentials_tenant_mapping:
  1343. jina_credentials_tenant_mapping[tenant_id] = []
  1344. jina_credentials_tenant_mapping[tenant_id].append(credential)
  1345. for tenant_id, credentials in jina_credentials_tenant_mapping.items():
  1346. # check jina plugin is installed
  1347. installed_plugins = installer_manager.list_plugins(tenant_id)
  1348. installed_plugins_ids = [plugin.plugin_id for plugin in installed_plugins]
  1349. if jina_plugin_id not in installed_plugins_ids:
  1350. if jina_plugin_unique_identifier:
  1351. # install jina plugin
  1352. print(jina_plugin_unique_identifier)
  1353. PluginService.install_from_marketplace_pkg(tenant_id, [jina_plugin_unique_identifier])
  1354. auth_count = 0
  1355. for credential in credentials:
  1356. auth_count += 1
  1357. # get credential api key
  1358. credentials_json = json.loads(credential.credentials)
  1359. api_key = credentials_json.get("config", {}).get("api_key")
  1360. new_credentials = {
  1361. "integration_secret": api_key,
  1362. }
  1363. datasource_provider = DatasourceProvider(
  1364. provider="jina",
  1365. tenant_id=tenant_id,
  1366. plugin_id=jina_plugin_id,
  1367. auth_type=api_key_credential_type.value,
  1368. encrypted_credentials=new_credentials,
  1369. name=f"Auth {auth_count}",
  1370. avatar_url="default",
  1371. is_default=False,
  1372. )
  1373. db.session.add(datasource_provider)
  1374. deal_jina_count += 1
  1375. db.session.commit()
  1376. except Exception as e:
  1377. click.echo(click.style(f"Error parsing client params: {str(e)}", fg="red"))
  1378. return
  1379. click.echo(click.style(f"Transforming notion successfully. deal_notion_count: {deal_notion_count}", fg="green"))
  1380. click.echo(
  1381. click.style(f"Transforming firecrawl successfully. deal_firecrawl_count: {deal_firecrawl_count}", fg="green")
  1382. )
  1383. click.echo(click.style(f"Transforming jina successfully. deal_jina_count: {deal_jina_count}", fg="green"))
  1384. @click.command("install-rag-pipeline-plugins", help="Install rag pipeline plugins.")
  1385. @click.option(
  1386. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  1387. )
  1388. @click.option(
  1389. "--output_file", prompt=True, help="The file to store the installed plugins.", default="installed_plugins.jsonl"
  1390. )
  1391. @click.option("--workers", prompt=True, help="The number of workers to install plugins.", default=100)
  1392. def install_rag_pipeline_plugins(input_file, output_file, workers):
  1393. """
  1394. Install rag pipeline plugins
  1395. """
  1396. click.echo(click.style("Installing rag pipeline plugins", fg="yellow"))
  1397. plugin_migration = PluginMigration()
  1398. plugin_migration.install_rag_pipeline_plugins(
  1399. input_file,
  1400. output_file,
  1401. workers,
  1402. )
  1403. click.echo(click.style("Installing rag pipeline plugins successfully", fg="green"))