Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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