You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. from typing import Any, Optional
  6. import click
  7. from flask import current_app
  8. from pydantic import TypeAdapter
  9. from sqlalchemy import select
  10. from werkzeug.exceptions import NotFound
  11. from configs import dify_config
  12. from constants.languages import languages
  13. from core.plugin.entities.plugin import ToolProviderID
  14. from core.rag.datasource.vdb.vector_factory import Vector
  15. from core.rag.datasource.vdb.vector_type import VectorType
  16. from core.rag.index_processor.constant.built_in_field import BuiltInField
  17. from core.rag.models.document import Document
  18. from core.tools.utils.system_oauth_encryption import encrypt_system_oauth_params
  19. from events.app_event import app_was_created
  20. from extensions.ext_database import db
  21. from extensions.ext_redis import redis_client
  22. from extensions.ext_storage import storage
  23. from libs.helper import email as email_validate
  24. from libs.password import hash_password, password_pattern, valid_password
  25. from libs.rsa import generate_key_pair
  26. from models import Tenant
  27. from models.dataset import Dataset, DatasetCollectionBinding, DatasetMetadata, DatasetMetadataBinding, DocumentSegment
  28. from models.dataset import Document as DatasetDocument
  29. from models.model import Account, App, AppAnnotationSetting, AppMode, Conversation, MessageAnnotation
  30. from models.provider import Provider, ProviderModel
  31. from models.tools import ToolOAuthSystemClient
  32. from services.account_service import AccountService, RegisterService, TenantService
  33. from services.clear_free_plan_tenant_expired_logs import ClearFreePlanTenantExpiredLogs
  34. from services.plugin.data_migration import PluginDataMigration
  35. from services.plugin.plugin_migration import PluginMigration
  36. @click.command("reset-password", help="Reset the account password.")
  37. @click.option("--email", prompt=True, help="Account email to reset password for")
  38. @click.option("--new-password", prompt=True, help="New password")
  39. @click.option("--password-confirm", prompt=True, help="Confirm new password")
  40. def reset_password(email, new_password, password_confirm):
  41. """
  42. Reset password of owner account
  43. Only available in SELF_HOSTED mode
  44. """
  45. if str(new_password).strip() != str(password_confirm).strip():
  46. click.echo(click.style("Passwords do not match.", fg="red"))
  47. return
  48. account = db.session.query(Account).filter(Account.email == email).one_or_none()
  49. if not account:
  50. click.echo(click.style("Account not found for email: {}".format(email), fg="red"))
  51. return
  52. try:
  53. valid_password(new_password)
  54. except:
  55. click.echo(click.style("Invalid password. Must match {}".format(password_pattern), fg="red"))
  56. return
  57. # generate password salt
  58. salt = secrets.token_bytes(16)
  59. base64_salt = base64.b64encode(salt).decode()
  60. # encrypt password with salt
  61. password_hashed = hash_password(new_password, salt)
  62. base64_password_hashed = base64.b64encode(password_hashed).decode()
  63. account.password = base64_password_hashed
  64. account.password_salt = base64_salt
  65. db.session.commit()
  66. AccountService.reset_login_error_rate_limit(email)
  67. click.echo(click.style("Password reset successfully.", fg="green"))
  68. @click.command("reset-email", help="Reset the account email.")
  69. @click.option("--email", prompt=True, help="Current account email")
  70. @click.option("--new-email", prompt=True, help="New email")
  71. @click.option("--email-confirm", prompt=True, help="Confirm new email")
  72. def reset_email(email, new_email, email_confirm):
  73. """
  74. Replace account email
  75. :return:
  76. """
  77. if str(new_email).strip() != str(email_confirm).strip():
  78. click.echo(click.style("New emails do not match.", fg="red"))
  79. return
  80. account = db.session.query(Account).filter(Account.email == email).one_or_none()
  81. if not account:
  82. click.echo(click.style("Account not found for email: {}".format(email), fg="red"))
  83. return
  84. try:
  85. email_validate(new_email)
  86. except:
  87. click.echo(click.style("Invalid email: {}".format(new_email), fg="red"))
  88. return
  89. account.email = new_email
  90. db.session.commit()
  91. click.echo(click.style("Email updated successfully.", fg="green"))
  92. @click.command(
  93. "reset-encrypt-key-pair",
  94. help="Reset the asymmetric key pair of workspace for encrypt LLM credentials. "
  95. "After the reset, all LLM credentials will become invalid, "
  96. "requiring re-entry."
  97. "Only support SELF_HOSTED mode.",
  98. )
  99. @click.confirmation_option(
  100. prompt=click.style(
  101. "Are you sure you want to reset encrypt key pair? This operation cannot be rolled back!", fg="red"
  102. )
  103. )
  104. def reset_encrypt_key_pair():
  105. """
  106. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  107. After the reset, all LLM credentials will become invalid, requiring re-entry.
  108. Only support SELF_HOSTED mode.
  109. """
  110. if dify_config.EDITION != "SELF_HOSTED":
  111. click.echo(click.style("This command is only for SELF_HOSTED installations.", fg="red"))
  112. return
  113. tenants = db.session.query(Tenant).all()
  114. for tenant in tenants:
  115. if not tenant:
  116. click.echo(click.style("No workspaces found. Run /install first.", fg="red"))
  117. return
  118. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  119. db.session.query(Provider).filter(Provider.provider_type == "custom", Provider.tenant_id == tenant.id).delete()
  120. db.session.query(ProviderModel).filter(ProviderModel.tenant_id == tenant.id).delete()
  121. db.session.commit()
  122. click.echo(
  123. click.style(
  124. "Congratulations! The asymmetric key pair of workspace {} has been reset.".format(tenant.id),
  125. fg="green",
  126. )
  127. )
  128. @click.command("vdb-migrate", help="Migrate vector db.")
  129. @click.option("--scope", default="all", prompt=False, help="The scope of vector database to migrate, Default is All.")
  130. def vdb_migrate(scope: str):
  131. if scope in {"knowledge", "all"}:
  132. migrate_knowledge_vector_database()
  133. if scope in {"annotation", "all"}:
  134. migrate_annotation_vector_database()
  135. def migrate_annotation_vector_database():
  136. """
  137. Migrate annotation datas to target vector database .
  138. """
  139. click.echo(click.style("Starting annotation data migration.", fg="green"))
  140. create_count = 0
  141. skipped_count = 0
  142. total_count = 0
  143. page = 1
  144. while True:
  145. try:
  146. # get apps info
  147. per_page = 50
  148. apps = (
  149. db.session.query(App)
  150. .filter(App.status == "normal")
  151. .order_by(App.created_at.desc())
  152. .limit(per_page)
  153. .offset((page - 1) * per_page)
  154. .all()
  155. )
  156. if not apps:
  157. break
  158. except NotFound:
  159. break
  160. page += 1
  161. for app in apps:
  162. total_count = total_count + 1
  163. click.echo(
  164. f"Processing the {total_count} app {app.id}. " + f"{create_count} created, {skipped_count} skipped."
  165. )
  166. try:
  167. click.echo("Creating app annotation index: {}".format(app.id))
  168. app_annotation_setting = (
  169. db.session.query(AppAnnotationSetting).filter(AppAnnotationSetting.app_id == app.id).first()
  170. )
  171. if not app_annotation_setting:
  172. skipped_count = skipped_count + 1
  173. click.echo("App annotation setting disabled: {}".format(app.id))
  174. continue
  175. # get dataset_collection_binding info
  176. dataset_collection_binding = (
  177. db.session.query(DatasetCollectionBinding)
  178. .filter(DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id)
  179. .first()
  180. )
  181. if not dataset_collection_binding:
  182. click.echo("App annotation collection binding not found: {}".format(app.id))
  183. continue
  184. annotations = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app.id).all()
  185. dataset = Dataset(
  186. id=app.id,
  187. tenant_id=app.tenant_id,
  188. indexing_technique="high_quality",
  189. embedding_model_provider=dataset_collection_binding.provider_name,
  190. embedding_model=dataset_collection_binding.model_name,
  191. collection_binding_id=dataset_collection_binding.id,
  192. )
  193. documents = []
  194. if annotations:
  195. for annotation in annotations:
  196. document = Document(
  197. page_content=annotation.question,
  198. metadata={"annotation_id": annotation.id, "app_id": app.id, "doc_id": annotation.id},
  199. )
  200. documents.append(document)
  201. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  202. click.echo(f"Migrating annotations for app: {app.id}.")
  203. try:
  204. vector.delete()
  205. click.echo(click.style(f"Deleted vector index for app {app.id}.", fg="green"))
  206. except Exception as e:
  207. click.echo(click.style(f"Failed to delete vector index for app {app.id}.", fg="red"))
  208. raise e
  209. if documents:
  210. try:
  211. click.echo(
  212. click.style(
  213. f"Creating vector index with {len(documents)} annotations for app {app.id}.",
  214. fg="green",
  215. )
  216. )
  217. vector.create(documents)
  218. click.echo(click.style(f"Created vector index for app {app.id}.", fg="green"))
  219. except Exception as e:
  220. click.echo(click.style(f"Failed to created vector index for app {app.id}.", fg="red"))
  221. raise e
  222. click.echo(f"Successfully migrated app annotation {app.id}.")
  223. create_count += 1
  224. except Exception as e:
  225. click.echo(
  226. click.style(
  227. "Error creating app annotation index: {} {}".format(e.__class__.__name__, str(e)), fg="red"
  228. )
  229. )
  230. continue
  231. click.echo(
  232. click.style(
  233. f"Migration complete. Created {create_count} app annotation indexes. Skipped {skipped_count} apps.",
  234. fg="green",
  235. )
  236. )
  237. def migrate_knowledge_vector_database():
  238. """
  239. Migrate vector database datas to target vector database .
  240. """
  241. click.echo(click.style("Starting vector database migration.", fg="green"))
  242. create_count = 0
  243. skipped_count = 0
  244. total_count = 0
  245. vector_type = dify_config.VECTOR_STORE
  246. upper_collection_vector_types = {
  247. VectorType.MILVUS,
  248. VectorType.PGVECTOR,
  249. VectorType.VASTBASE,
  250. VectorType.RELYT,
  251. VectorType.WEAVIATE,
  252. VectorType.ORACLE,
  253. VectorType.ELASTICSEARCH,
  254. VectorType.OPENGAUSS,
  255. VectorType.TABLESTORE,
  256. VectorType.MATRIXONE,
  257. }
  258. lower_collection_vector_types = {
  259. VectorType.ANALYTICDB,
  260. VectorType.CHROMA,
  261. VectorType.MYSCALE,
  262. VectorType.PGVECTO_RS,
  263. VectorType.TIDB_VECTOR,
  264. VectorType.OPENSEARCH,
  265. VectorType.TENCENT,
  266. VectorType.BAIDU,
  267. VectorType.VIKINGDB,
  268. VectorType.UPSTASH,
  269. VectorType.COUCHBASE,
  270. VectorType.OCEANBASE,
  271. }
  272. page = 1
  273. while True:
  274. try:
  275. stmt = (
  276. select(Dataset).filter(Dataset.indexing_technique == "high_quality").order_by(Dataset.created_at.desc())
  277. )
  278. datasets = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  279. except NotFound:
  280. break
  281. page += 1
  282. for dataset in datasets:
  283. total_count = total_count + 1
  284. click.echo(
  285. f"Processing the {total_count} dataset {dataset.id}. {create_count} created, {skipped_count} skipped."
  286. )
  287. try:
  288. click.echo("Creating dataset vector database index: {}".format(dataset.id))
  289. if dataset.index_struct_dict:
  290. if dataset.index_struct_dict["type"] == vector_type:
  291. skipped_count = skipped_count + 1
  292. continue
  293. collection_name = ""
  294. dataset_id = dataset.id
  295. if vector_type in upper_collection_vector_types:
  296. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  297. elif vector_type == VectorType.QDRANT:
  298. if dataset.collection_binding_id:
  299. dataset_collection_binding = (
  300. db.session.query(DatasetCollectionBinding)
  301. .filter(DatasetCollectionBinding.id == dataset.collection_binding_id)
  302. .one_or_none()
  303. )
  304. if dataset_collection_binding:
  305. collection_name = dataset_collection_binding.collection_name
  306. else:
  307. raise ValueError("Dataset Collection Binding not found")
  308. else:
  309. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  310. elif vector_type in lower_collection_vector_types:
  311. collection_name = Dataset.gen_collection_name_by_id(dataset_id).lower()
  312. else:
  313. raise ValueError(f"Vector store {vector_type} is not supported.")
  314. index_struct_dict = {"type": vector_type, "vector_store": {"class_prefix": collection_name}}
  315. dataset.index_struct = json.dumps(index_struct_dict)
  316. vector = Vector(dataset)
  317. click.echo(f"Migrating dataset {dataset.id}.")
  318. try:
  319. vector.delete()
  320. click.echo(
  321. click.style(f"Deleted vector index {collection_name} for dataset {dataset.id}.", fg="green")
  322. )
  323. except Exception as e:
  324. click.echo(
  325. click.style(
  326. f"Failed to delete vector index {collection_name} for dataset {dataset.id}.", fg="red"
  327. )
  328. )
  329. raise e
  330. dataset_documents = (
  331. db.session.query(DatasetDocument)
  332. .filter(
  333. DatasetDocument.dataset_id == dataset.id,
  334. DatasetDocument.indexing_status == "completed",
  335. DatasetDocument.enabled == True,
  336. DatasetDocument.archived == False,
  337. )
  338. .all()
  339. )
  340. documents = []
  341. segments_count = 0
  342. for dataset_document in dataset_documents:
  343. segments = (
  344. db.session.query(DocumentSegment)
  345. .filter(
  346. DocumentSegment.document_id == dataset_document.id,
  347. DocumentSegment.status == "completed",
  348. DocumentSegment.enabled == True,
  349. )
  350. .all()
  351. )
  352. for segment in segments:
  353. document = Document(
  354. page_content=segment.content,
  355. metadata={
  356. "doc_id": segment.index_node_id,
  357. "doc_hash": segment.index_node_hash,
  358. "document_id": segment.document_id,
  359. "dataset_id": segment.dataset_id,
  360. },
  361. )
  362. documents.append(document)
  363. segments_count = segments_count + 1
  364. if documents:
  365. try:
  366. click.echo(
  367. click.style(
  368. f"Creating vector index with {len(documents)} documents of {segments_count}"
  369. f" segments for dataset {dataset.id}.",
  370. fg="green",
  371. )
  372. )
  373. vector.create(documents)
  374. click.echo(click.style(f"Created vector index for dataset {dataset.id}.", fg="green"))
  375. except Exception as e:
  376. click.echo(click.style(f"Failed to created vector index for dataset {dataset.id}.", fg="red"))
  377. raise e
  378. db.session.add(dataset)
  379. db.session.commit()
  380. click.echo(f"Successfully migrated dataset {dataset.id}.")
  381. create_count += 1
  382. except Exception as e:
  383. db.session.rollback()
  384. click.echo(
  385. click.style("Error creating dataset index: {} {}".format(e.__class__.__name__, str(e)), fg="red")
  386. )
  387. continue
  388. click.echo(
  389. click.style(
  390. f"Migration complete. Created {create_count} dataset indexes. Skipped {skipped_count} datasets.", fg="green"
  391. )
  392. )
  393. @click.command("convert-to-agent-apps", help="Convert Agent Assistant to Agent App.")
  394. def convert_to_agent_apps():
  395. """
  396. Convert Agent Assistant to Agent App.
  397. """
  398. click.echo(click.style("Starting convert to agent apps.", fg="green"))
  399. proceeded_app_ids = []
  400. while True:
  401. # fetch first 1000 apps
  402. sql_query = """SELECT a.id AS id FROM apps a
  403. INNER JOIN app_model_configs am ON a.app_model_config_id=am.id
  404. WHERE a.mode = 'chat'
  405. AND am.agent_mode is not null
  406. AND (
  407. am.agent_mode like '%"strategy": "function_call"%'
  408. OR am.agent_mode like '%"strategy": "react"%'
  409. )
  410. AND (
  411. am.agent_mode like '{"enabled": true%'
  412. OR am.agent_mode like '{"max_iteration": %'
  413. ) ORDER BY a.created_at DESC LIMIT 1000
  414. """
  415. with db.engine.begin() as conn:
  416. rs = conn.execute(db.text(sql_query))
  417. apps = []
  418. for i in rs:
  419. app_id = str(i.id)
  420. if app_id not in proceeded_app_ids:
  421. proceeded_app_ids.append(app_id)
  422. app = db.session.query(App).filter(App.id == app_id).first()
  423. if app is not None:
  424. apps.append(app)
  425. if len(apps) == 0:
  426. break
  427. for app in apps:
  428. click.echo("Converting app: {}".format(app.id))
  429. try:
  430. app.mode = AppMode.AGENT_CHAT.value
  431. db.session.commit()
  432. # update conversation mode to agent
  433. db.session.query(Conversation).filter(Conversation.app_id == app.id).update(
  434. {Conversation.mode: AppMode.AGENT_CHAT.value}
  435. )
  436. db.session.commit()
  437. click.echo(click.style("Converted app: {}".format(app.id), fg="green"))
  438. except Exception as e:
  439. click.echo(click.style("Convert app error: {} {}".format(e.__class__.__name__, str(e)), fg="red"))
  440. click.echo(click.style("Conversion complete. Converted {} agent apps.".format(len(proceeded_app_ids)), fg="green"))
  441. @click.command("add-qdrant-index", help="Add Qdrant index.")
  442. @click.option("--field", default="metadata.doc_id", prompt=False, help="Index field , default is metadata.doc_id.")
  443. def add_qdrant_index(field: str):
  444. click.echo(click.style("Starting Qdrant index creation.", fg="green"))
  445. create_count = 0
  446. try:
  447. bindings = db.session.query(DatasetCollectionBinding).all()
  448. if not bindings:
  449. click.echo(click.style("No dataset collection bindings found.", fg="red"))
  450. return
  451. import qdrant_client
  452. from qdrant_client.http.exceptions import UnexpectedResponse
  453. from qdrant_client.http.models import PayloadSchemaType
  454. from core.rag.datasource.vdb.qdrant.qdrant_vector import QdrantConfig
  455. for binding in bindings:
  456. if dify_config.QDRANT_URL is None:
  457. raise ValueError("Qdrant URL is required.")
  458. qdrant_config = QdrantConfig(
  459. endpoint=dify_config.QDRANT_URL,
  460. api_key=dify_config.QDRANT_API_KEY,
  461. root_path=current_app.root_path,
  462. timeout=dify_config.QDRANT_CLIENT_TIMEOUT,
  463. grpc_port=dify_config.QDRANT_GRPC_PORT,
  464. prefer_grpc=dify_config.QDRANT_GRPC_ENABLED,
  465. )
  466. try:
  467. client = qdrant_client.QdrantClient(**qdrant_config.to_qdrant_params())
  468. # create payload index
  469. client.create_payload_index(binding.collection_name, field, field_schema=PayloadSchemaType.KEYWORD)
  470. create_count += 1
  471. except UnexpectedResponse as e:
  472. # Collection does not exist, so return
  473. if e.status_code == 404:
  474. click.echo(click.style(f"Collection not found: {binding.collection_name}.", fg="red"))
  475. continue
  476. # Some other error occurred, so re-raise the exception
  477. else:
  478. click.echo(
  479. click.style(
  480. f"Failed to create Qdrant index for collection: {binding.collection_name}.", fg="red"
  481. )
  482. )
  483. except Exception:
  484. click.echo(click.style("Failed to create Qdrant client.", fg="red"))
  485. click.echo(click.style(f"Index creation complete. Created {create_count} collection indexes.", fg="green"))
  486. @click.command("old-metadata-migration", help="Old metadata migration.")
  487. def old_metadata_migration():
  488. """
  489. Old metadata migration.
  490. """
  491. click.echo(click.style("Starting old metadata migration.", fg="green"))
  492. page = 1
  493. while True:
  494. try:
  495. stmt = (
  496. select(DatasetDocument)
  497. .filter(DatasetDocument.doc_metadata.is_not(None))
  498. .order_by(DatasetDocument.created_at.desc())
  499. )
  500. documents = db.paginate(select=stmt, page=page, per_page=50, max_per_page=50, error_out=False)
  501. except NotFound:
  502. break
  503. if not documents:
  504. break
  505. for document in documents:
  506. if document.doc_metadata:
  507. doc_metadata = document.doc_metadata
  508. for key, value in doc_metadata.items():
  509. for field in BuiltInField:
  510. if field.value == key:
  511. break
  512. else:
  513. dataset_metadata = (
  514. db.session.query(DatasetMetadata)
  515. .filter(DatasetMetadata.dataset_id == document.dataset_id, DatasetMetadata.name == key)
  516. .first()
  517. )
  518. if not dataset_metadata:
  519. dataset_metadata = DatasetMetadata(
  520. tenant_id=document.tenant_id,
  521. dataset_id=document.dataset_id,
  522. name=key,
  523. type="string",
  524. created_by=document.created_by,
  525. )
  526. db.session.add(dataset_metadata)
  527. db.session.flush()
  528. dataset_metadata_binding = DatasetMetadataBinding(
  529. tenant_id=document.tenant_id,
  530. dataset_id=document.dataset_id,
  531. metadata_id=dataset_metadata.id,
  532. document_id=document.id,
  533. created_by=document.created_by,
  534. )
  535. db.session.add(dataset_metadata_binding)
  536. else:
  537. dataset_metadata_binding = (
  538. db.session.query(DatasetMetadataBinding) # type: ignore
  539. .filter(
  540. DatasetMetadataBinding.dataset_id == document.dataset_id,
  541. DatasetMetadataBinding.document_id == document.id,
  542. DatasetMetadataBinding.metadata_id == dataset_metadata.id,
  543. )
  544. .first()
  545. )
  546. if not dataset_metadata_binding:
  547. dataset_metadata_binding = DatasetMetadataBinding(
  548. tenant_id=document.tenant_id,
  549. dataset_id=document.dataset_id,
  550. metadata_id=dataset_metadata.id,
  551. document_id=document.id,
  552. created_by=document.created_by,
  553. )
  554. db.session.add(dataset_metadata_binding)
  555. db.session.commit()
  556. page += 1
  557. click.echo(click.style("Old metadata migration completed.", fg="green"))
  558. @click.command("create-tenant", help="Create account and tenant.")
  559. @click.option("--email", prompt=True, help="Tenant account email.")
  560. @click.option("--name", prompt=True, help="Workspace name.")
  561. @click.option("--language", prompt=True, help="Account language, default: en-US.")
  562. def create_tenant(email: str, language: Optional[str] = None, name: Optional[str] = None):
  563. """
  564. Create tenant account
  565. """
  566. if not email:
  567. click.echo(click.style("Email is required.", fg="red"))
  568. return
  569. # Create account
  570. email = email.strip()
  571. if "@" not in email:
  572. click.echo(click.style("Invalid email address.", fg="red"))
  573. return
  574. account_name = email.split("@")[0]
  575. if language not in languages:
  576. language = "en-US"
  577. # Validates name encoding for non-Latin characters.
  578. name = name.strip().encode("utf-8").decode("utf-8") if name else None
  579. # generate random password
  580. new_password = secrets.token_urlsafe(16)
  581. # register account
  582. account = RegisterService.register(
  583. email=email,
  584. name=account_name,
  585. password=new_password,
  586. language=language,
  587. create_workspace_required=False,
  588. )
  589. TenantService.create_owner_tenant_if_not_exist(account, name)
  590. click.echo(
  591. click.style(
  592. "Account and tenant created.\nAccount: {}\nPassword: {}".format(email, new_password),
  593. fg="green",
  594. )
  595. )
  596. @click.command("upgrade-db", help="Upgrade the database")
  597. def upgrade_db():
  598. click.echo("Preparing database migration...")
  599. lock = redis_client.lock(name="db_upgrade_lock", timeout=60)
  600. if lock.acquire(blocking=False):
  601. try:
  602. click.echo(click.style("Starting database migration.", fg="green"))
  603. # run db migration
  604. import flask_migrate
  605. flask_migrate.upgrade()
  606. click.echo(click.style("Database migration successful!", fg="green"))
  607. except Exception:
  608. logging.exception("Failed to execute database migration")
  609. finally:
  610. lock.release()
  611. else:
  612. click.echo("Database migration skipped")
  613. @click.command("fix-app-site-missing", help="Fix app related site missing issue.")
  614. def fix_app_site_missing():
  615. """
  616. Fix app related site missing issue.
  617. """
  618. click.echo(click.style("Starting fix for missing app-related sites.", fg="green"))
  619. failed_app_ids = []
  620. while True:
  621. sql = """select apps.id as id from apps left join sites on sites.app_id=apps.id
  622. where sites.id is null limit 1000"""
  623. with db.engine.begin() as conn:
  624. rs = conn.execute(db.text(sql))
  625. processed_count = 0
  626. for i in rs:
  627. processed_count += 1
  628. app_id = str(i.id)
  629. if app_id in failed_app_ids:
  630. continue
  631. try:
  632. app = db.session.query(App).filter(App.id == app_id).first()
  633. if not app:
  634. print(f"App {app_id} not found")
  635. continue
  636. tenant = app.tenant
  637. if tenant:
  638. accounts = tenant.get_accounts()
  639. if not accounts:
  640. print("Fix failed for app {}".format(app.id))
  641. continue
  642. account = accounts[0]
  643. print("Fixing missing site for app {}".format(app.id))
  644. app_was_created.send(app, account=account)
  645. except Exception:
  646. failed_app_ids.append(app_id)
  647. click.echo(click.style("Failed to fix missing site for app {}".format(app_id), fg="red"))
  648. logging.exception(f"Failed to fix app related site missing issue, app_id: {app_id}")
  649. continue
  650. if not processed_count:
  651. break
  652. click.echo(click.style("Fix for missing app-related sites completed successfully!", fg="green"))
  653. @click.command("migrate-data-for-plugin", help="Migrate data for plugin.")
  654. def migrate_data_for_plugin():
  655. """
  656. Migrate data for plugin.
  657. """
  658. click.echo(click.style("Starting migrate data for plugin.", fg="white"))
  659. PluginDataMigration.migrate()
  660. click.echo(click.style("Migrate data for plugin completed.", fg="green"))
  661. @click.command("extract-plugins", help="Extract plugins.")
  662. @click.option("--output_file", prompt=True, help="The file to store the extracted plugins.", default="plugins.jsonl")
  663. @click.option("--workers", prompt=True, help="The number of workers to extract plugins.", default=10)
  664. def extract_plugins(output_file: str, workers: int):
  665. """
  666. Extract plugins.
  667. """
  668. click.echo(click.style("Starting extract plugins.", fg="white"))
  669. PluginMigration.extract_plugins(output_file, workers)
  670. click.echo(click.style("Extract plugins completed.", fg="green"))
  671. @click.command("extract-unique-identifiers", help="Extract unique identifiers.")
  672. @click.option(
  673. "--output_file",
  674. prompt=True,
  675. help="The file to store the extracted unique identifiers.",
  676. default="unique_identifiers.json",
  677. )
  678. @click.option(
  679. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  680. )
  681. def extract_unique_plugins(output_file: str, input_file: str):
  682. """
  683. Extract unique plugins.
  684. """
  685. click.echo(click.style("Starting extract unique plugins.", fg="white"))
  686. PluginMigration.extract_unique_plugins_to_file(input_file, output_file)
  687. click.echo(click.style("Extract unique plugins completed.", fg="green"))
  688. @click.command("install-plugins", help="Install plugins.")
  689. @click.option(
  690. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  691. )
  692. @click.option(
  693. "--output_file", prompt=True, help="The file to store the installed plugins.", default="installed_plugins.jsonl"
  694. )
  695. @click.option("--workers", prompt=True, help="The number of workers to install plugins.", default=100)
  696. def install_plugins(input_file: str, output_file: str, workers: int):
  697. """
  698. Install plugins.
  699. """
  700. click.echo(click.style("Starting install plugins.", fg="white"))
  701. PluginMigration.install_plugins(input_file, output_file, workers)
  702. click.echo(click.style("Install plugins completed.", fg="green"))
  703. @click.command("clear-free-plan-tenant-expired-logs", help="Clear free plan tenant expired logs.")
  704. @click.option("--days", prompt=True, help="The days to clear free plan tenant expired logs.", default=30)
  705. @click.option("--batch", prompt=True, help="The batch size to clear free plan tenant expired logs.", default=100)
  706. @click.option(
  707. "--tenant_ids",
  708. prompt=True,
  709. multiple=True,
  710. help="The tenant ids to clear free plan tenant expired logs.",
  711. )
  712. def clear_free_plan_tenant_expired_logs(days: int, batch: int, tenant_ids: list[str]):
  713. """
  714. Clear free plan tenant expired logs.
  715. """
  716. click.echo(click.style("Starting clear free plan tenant expired logs.", fg="white"))
  717. ClearFreePlanTenantExpiredLogs.process(days, batch, tenant_ids)
  718. click.echo(click.style("Clear free plan tenant expired logs completed.", fg="green"))
  719. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  720. @click.command("clear-orphaned-file-records", help="Clear orphaned file records.")
  721. def clear_orphaned_file_records(force: bool):
  722. """
  723. Clear orphaned file records in the database.
  724. """
  725. # define tables and columns to process
  726. files_tables = [
  727. {"table": "upload_files", "id_column": "id", "key_column": "key"},
  728. {"table": "tool_files", "id_column": "id", "key_column": "file_key"},
  729. ]
  730. ids_tables = [
  731. {"type": "uuid", "table": "message_files", "column": "upload_file_id"},
  732. {"type": "text", "table": "documents", "column": "data_source_info"},
  733. {"type": "text", "table": "document_segments", "column": "content"},
  734. {"type": "text", "table": "messages", "column": "answer"},
  735. {"type": "text", "table": "workflow_node_executions", "column": "inputs"},
  736. {"type": "text", "table": "workflow_node_executions", "column": "process_data"},
  737. {"type": "text", "table": "workflow_node_executions", "column": "outputs"},
  738. {"type": "text", "table": "conversations", "column": "introduction"},
  739. {"type": "text", "table": "conversations", "column": "system_instruction"},
  740. {"type": "text", "table": "accounts", "column": "avatar"},
  741. {"type": "text", "table": "apps", "column": "icon"},
  742. {"type": "text", "table": "sites", "column": "icon"},
  743. {"type": "json", "table": "messages", "column": "inputs"},
  744. {"type": "json", "table": "messages", "column": "message"},
  745. ]
  746. # notify user and ask for confirmation
  747. click.echo(
  748. click.style(
  749. "This command will first find and delete orphaned file records from the message_files table,", fg="yellow"
  750. )
  751. )
  752. click.echo(
  753. click.style(
  754. "and then it will find and delete orphaned file records in the following tables:",
  755. fg="yellow",
  756. )
  757. )
  758. for files_table in files_tables:
  759. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  760. click.echo(
  761. click.style("The following tables and columns will be scanned to find orphaned file records:", fg="yellow")
  762. )
  763. for ids_table in ids_tables:
  764. click.echo(click.style(f"- {ids_table['table']} ({ids_table['column']})", fg="yellow"))
  765. click.echo("")
  766. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  767. click.echo(
  768. click.style(
  769. (
  770. "Since not all patterns have been fully tested, "
  771. "please note that this command may delete unintended file records."
  772. ),
  773. fg="yellow",
  774. )
  775. )
  776. click.echo(
  777. click.style("This cannot be undone. Please make sure to back up your database before proceeding.", fg="yellow")
  778. )
  779. click.echo(
  780. click.style(
  781. (
  782. "It is also recommended to run this during the maintenance window, "
  783. "as this may cause high load on your instance."
  784. ),
  785. fg="yellow",
  786. )
  787. )
  788. if not force:
  789. click.confirm("Do you want to proceed?", abort=True)
  790. # start the cleanup process
  791. click.echo(click.style("Starting orphaned file records cleanup.", fg="white"))
  792. # clean up the orphaned records in the message_files table where message_id doesn't exist in messages table
  793. try:
  794. click.echo(
  795. click.style("- Listing message_files records where message_id doesn't exist in messages table", fg="white")
  796. )
  797. query = (
  798. "SELECT mf.id, mf.message_id "
  799. "FROM message_files mf LEFT JOIN messages m ON mf.message_id = m.id "
  800. "WHERE m.id IS NULL"
  801. )
  802. orphaned_message_files = []
  803. with db.engine.begin() as conn:
  804. rs = conn.execute(db.text(query))
  805. for i in rs:
  806. orphaned_message_files.append({"id": str(i[0]), "message_id": str(i[1])})
  807. if orphaned_message_files:
  808. click.echo(click.style(f"Found {len(orphaned_message_files)} orphaned message_files records:", fg="white"))
  809. for record in orphaned_message_files:
  810. click.echo(click.style(f" - id: {record['id']}, message_id: {record['message_id']}", fg="black"))
  811. if not force:
  812. click.confirm(
  813. (
  814. f"Do you want to proceed "
  815. f"to delete all {len(orphaned_message_files)} orphaned message_files records?"
  816. ),
  817. abort=True,
  818. )
  819. click.echo(click.style("- Deleting orphaned message_files records", fg="white"))
  820. query = "DELETE FROM message_files WHERE id IN :ids"
  821. with db.engine.begin() as conn:
  822. conn.execute(db.text(query), {"ids": tuple([record["id"] for record in orphaned_message_files])})
  823. click.echo(
  824. click.style(f"Removed {len(orphaned_message_files)} orphaned message_files records.", fg="green")
  825. )
  826. else:
  827. click.echo(click.style("No orphaned message_files records found. There is nothing to delete.", fg="green"))
  828. except Exception as e:
  829. click.echo(click.style(f"Error deleting orphaned message_files records: {str(e)}", fg="red"))
  830. # clean up the orphaned records in the rest of the *_files tables
  831. try:
  832. # fetch file id and keys from each table
  833. all_files_in_tables = []
  834. for files_table in files_tables:
  835. click.echo(click.style(f"- Listing file records in table {files_table['table']}", fg="white"))
  836. query = f"SELECT {files_table['id_column']}, {files_table['key_column']} FROM {files_table['table']}"
  837. with db.engine.begin() as conn:
  838. rs = conn.execute(db.text(query))
  839. for i in rs:
  840. all_files_in_tables.append({"table": files_table["table"], "id": str(i[0]), "key": i[1]})
  841. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  842. # fetch referred table and columns
  843. 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}"
  844. all_ids_in_tables = []
  845. for ids_table in ids_tables:
  846. query = ""
  847. if ids_table["type"] == "uuid":
  848. click.echo(
  849. click.style(
  850. f"- Listing file ids in column {ids_table['column']} in table {ids_table['table']}", fg="white"
  851. )
  852. )
  853. query = (
  854. f"SELECT {ids_table['column']} FROM {ids_table['table']} WHERE {ids_table['column']} IS NOT NULL"
  855. )
  856. with db.engine.begin() as conn:
  857. rs = conn.execute(db.text(query))
  858. for i in rs:
  859. all_ids_in_tables.append({"table": ids_table["table"], "id": str(i[0])})
  860. elif ids_table["type"] == "text":
  861. click.echo(
  862. click.style(
  863. f"- Listing file-id-like strings in column {ids_table['column']} in table {ids_table['table']}",
  864. fg="white",
  865. )
  866. )
  867. query = (
  868. f"SELECT regexp_matches({ids_table['column']}, '{guid_regexp}', 'g') AS extracted_id "
  869. f"FROM {ids_table['table']}"
  870. )
  871. with db.engine.begin() as conn:
  872. rs = conn.execute(db.text(query))
  873. for i in rs:
  874. for j in i[0]:
  875. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  876. elif ids_table["type"] == "json":
  877. click.echo(
  878. click.style(
  879. (
  880. f"- Listing file-id-like JSON string in column {ids_table['column']} "
  881. f"in table {ids_table['table']}"
  882. ),
  883. fg="white",
  884. )
  885. )
  886. query = (
  887. f"SELECT regexp_matches({ids_table['column']}::text, '{guid_regexp}', 'g') AS extracted_id "
  888. f"FROM {ids_table['table']}"
  889. )
  890. with db.engine.begin() as conn:
  891. rs = conn.execute(db.text(query))
  892. for i in rs:
  893. for j in i[0]:
  894. all_ids_in_tables.append({"table": ids_table["table"], "id": j})
  895. click.echo(click.style(f"Found {len(all_ids_in_tables)} file ids in tables.", fg="white"))
  896. except Exception as e:
  897. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  898. return
  899. # find orphaned files
  900. all_files = [file["id"] for file in all_files_in_tables]
  901. all_ids = [file["id"] for file in all_ids_in_tables]
  902. orphaned_files = list(set(all_files) - set(all_ids))
  903. if not orphaned_files:
  904. click.echo(click.style("No orphaned file records found. There is nothing to delete.", fg="green"))
  905. return
  906. click.echo(click.style(f"Found {len(orphaned_files)} orphaned file records.", fg="white"))
  907. for file in orphaned_files:
  908. click.echo(click.style(f"- orphaned file id: {file}", fg="black"))
  909. if not force:
  910. click.confirm(f"Do you want to proceed to delete all {len(orphaned_files)} orphaned file records?", abort=True)
  911. # delete orphaned records for each file
  912. try:
  913. for files_table in files_tables:
  914. click.echo(click.style(f"- Deleting orphaned file records in table {files_table['table']}", fg="white"))
  915. query = f"DELETE FROM {files_table['table']} WHERE {files_table['id_column']} IN :ids"
  916. with db.engine.begin() as conn:
  917. conn.execute(db.text(query), {"ids": tuple(orphaned_files)})
  918. except Exception as e:
  919. click.echo(click.style(f"Error deleting orphaned file records: {str(e)}", fg="red"))
  920. return
  921. click.echo(click.style(f"Removed {len(orphaned_files)} orphaned file records.", fg="green"))
  922. @click.option("-f", "--force", is_flag=True, help="Skip user confirmation and force the command to execute.")
  923. @click.command("remove-orphaned-files-on-storage", help="Remove orphaned files on the storage.")
  924. def remove_orphaned_files_on_storage(force: bool):
  925. """
  926. Remove orphaned files on the storage.
  927. """
  928. # define tables and columns to process
  929. files_tables = [
  930. {"table": "upload_files", "key_column": "key"},
  931. {"table": "tool_files", "key_column": "file_key"},
  932. ]
  933. storage_paths = ["image_files", "tools", "upload_files"]
  934. # notify user and ask for confirmation
  935. click.echo(click.style("This command will find and remove orphaned files on the storage,", fg="yellow"))
  936. click.echo(
  937. click.style("by comparing the files on the storage with the records in the following tables:", fg="yellow")
  938. )
  939. for files_table in files_tables:
  940. click.echo(click.style(f"- {files_table['table']}", fg="yellow"))
  941. click.echo(click.style("The following paths on the storage will be scanned to find orphaned files:", fg="yellow"))
  942. for storage_path in storage_paths:
  943. click.echo(click.style(f"- {storage_path}", fg="yellow"))
  944. click.echo("")
  945. click.echo(click.style("!!! USE WITH CAUTION !!!", fg="red"))
  946. click.echo(
  947. click.style(
  948. "Currently, this command will work only for opendal based storage (STORAGE_TYPE=opendal).", fg="yellow"
  949. )
  950. )
  951. click.echo(
  952. click.style(
  953. "Since not all patterns have been fully tested, please note that this command may delete unintended files.",
  954. fg="yellow",
  955. )
  956. )
  957. click.echo(
  958. click.style("This cannot be undone. Please make sure to back up your storage before proceeding.", fg="yellow")
  959. )
  960. click.echo(
  961. click.style(
  962. (
  963. "It is also recommended to run this during the maintenance window, "
  964. "as this may cause high load on your instance."
  965. ),
  966. fg="yellow",
  967. )
  968. )
  969. if not force:
  970. click.confirm("Do you want to proceed?", abort=True)
  971. # start the cleanup process
  972. click.echo(click.style("Starting orphaned files cleanup.", fg="white"))
  973. # fetch file id and keys from each table
  974. all_files_in_tables = []
  975. try:
  976. for files_table in files_tables:
  977. click.echo(click.style(f"- Listing files from table {files_table['table']}", fg="white"))
  978. query = f"SELECT {files_table['key_column']} FROM {files_table['table']}"
  979. with db.engine.begin() as conn:
  980. rs = conn.execute(db.text(query))
  981. for i in rs:
  982. all_files_in_tables.append(str(i[0]))
  983. click.echo(click.style(f"Found {len(all_files_in_tables)} files in tables.", fg="white"))
  984. except Exception as e:
  985. click.echo(click.style(f"Error fetching keys: {str(e)}", fg="red"))
  986. all_files_on_storage = []
  987. for storage_path in storage_paths:
  988. try:
  989. click.echo(click.style(f"- Scanning files on storage path {storage_path}", fg="white"))
  990. files = storage.scan(path=storage_path, files=True, directories=False)
  991. all_files_on_storage.extend(files)
  992. except FileNotFoundError as e:
  993. click.echo(click.style(f" -> Skipping path {storage_path} as it does not exist.", fg="yellow"))
  994. continue
  995. except Exception as e:
  996. click.echo(click.style(f" -> Error scanning files on storage path {storage_path}: {str(e)}", fg="red"))
  997. continue
  998. click.echo(click.style(f"Found {len(all_files_on_storage)} files on storage.", fg="white"))
  999. # find orphaned files
  1000. orphaned_files = list(set(all_files_on_storage) - set(all_files_in_tables))
  1001. if not orphaned_files:
  1002. click.echo(click.style("No orphaned files found. There is nothing to remove.", fg="green"))
  1003. return
  1004. click.echo(click.style(f"Found {len(orphaned_files)} orphaned files.", fg="white"))
  1005. for file in orphaned_files:
  1006. click.echo(click.style(f"- orphaned file: {file}", fg="black"))
  1007. if not force:
  1008. click.confirm(f"Do you want to proceed to remove all {len(orphaned_files)} orphaned files?", abort=True)
  1009. # delete orphaned files
  1010. removed_files = 0
  1011. error_files = 0
  1012. for file in orphaned_files:
  1013. try:
  1014. storage.delete(file)
  1015. removed_files += 1
  1016. click.echo(click.style(f"- Removing orphaned file: {file}", fg="white"))
  1017. except Exception as e:
  1018. error_files += 1
  1019. click.echo(click.style(f"- Error deleting orphaned file {file}: {str(e)}", fg="red"))
  1020. continue
  1021. if error_files == 0:
  1022. click.echo(click.style(f"Removed {removed_files} orphaned files without errors.", fg="green"))
  1023. else:
  1024. click.echo(click.style(f"Removed {removed_files} orphaned files, with {error_files} errors.", fg="yellow"))
  1025. @click.command("setup-system-tool-oauth-client", help="Setup system tool oauth client.")
  1026. @click.option("--provider", prompt=True, help="Provider name")
  1027. @click.option("--client-params", prompt=True, help="Client Params")
  1028. def setup_system_tool_oauth_client(provider, client_params):
  1029. """
  1030. Setup system tool oauth client
  1031. """
  1032. provider_id = ToolProviderID(provider)
  1033. provider_name = provider_id.provider_name
  1034. plugin_id = provider_id.plugin_id
  1035. try:
  1036. # json validate
  1037. click.echo(click.style(f"Validating client params: {client_params}", fg="yellow"))
  1038. client_params_dict = TypeAdapter(dict[str, Any]).validate_json(client_params)
  1039. click.echo(click.style("Client params validated successfully.", fg="green"))
  1040. click.echo(click.style(f"Encrypting client params: {client_params}", fg="yellow"))
  1041. click.echo(click.style(f"Using SECRET_KEY: `{dify_config.SECRET_KEY}`", fg="yellow"))
  1042. oauth_client_params = encrypt_system_oauth_params(client_params_dict)
  1043. click.echo(click.style("Client params encrypted successfully.", fg="green"))
  1044. except Exception as e:
  1045. click.echo(click.style(f"Error parsing client params: {str(e)}", fg="red"))
  1046. return
  1047. deleted_count = (
  1048. db.session.query(ToolOAuthSystemClient)
  1049. .filter_by(
  1050. provider=provider_name,
  1051. plugin_id=plugin_id,
  1052. )
  1053. .delete()
  1054. )
  1055. if deleted_count > 0:
  1056. click.echo(click.style(f"Deleted {deleted_count} existing oauth client params.", fg="yellow"))
  1057. oauth_client = ToolOAuthSystemClient(
  1058. provider=provider_name,
  1059. plugin_id=plugin_id,
  1060. encrypted_oauth_params=oauth_client_params,
  1061. )
  1062. db.session.add(oauth_client)
  1063. db.session.commit()
  1064. click.echo(click.style(f"OAuth client params setup successfully. id: {oauth_client.id}", fg="green"))