commands.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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 werkzeug.exceptions import NotFound
  9. from configs import dify_config
  10. from constants.languages import languages
  11. from core.rag.datasource.vdb.vector_factory import Vector
  12. from core.rag.datasource.vdb.vector_type import VectorType
  13. from core.rag.index_processor.constant.built_in_field import BuiltInField
  14. from core.rag.models.document import Document
  15. from events.app_event import app_was_created
  16. from extensions.ext_database import db
  17. from extensions.ext_redis import redis_client
  18. from libs.helper import email as email_validate
  19. from libs.password import hash_password, password_pattern, valid_password
  20. from libs.rsa import generate_key_pair
  21. from models import Tenant
  22. from models.dataset import Dataset, DatasetCollectionBinding, DatasetMetadata, DatasetMetadataBinding, DocumentSegment
  23. from models.dataset import Document as DatasetDocument
  24. from models.model import Account, App, AppAnnotationSetting, AppMode, Conversation, MessageAnnotation
  25. from models.provider import Provider, ProviderModel
  26. from services.account_service import RegisterService, TenantService
  27. from services.clear_free_plan_tenant_expired_logs import ClearFreePlanTenantExpiredLogs
  28. from services.plugin.data_migration import PluginDataMigration
  29. from services.plugin.plugin_migration import PluginMigration
  30. @click.command("reset-password", help="Reset the account password.")
  31. @click.option("--email", prompt=True, help="Account email to reset password for")
  32. @click.option("--new-password", prompt=True, help="New password")
  33. @click.option("--password-confirm", prompt=True, help="Confirm new password")
  34. def reset_password(email, new_password, password_confirm):
  35. """
  36. Reset password of owner account
  37. Only available in SELF_HOSTED mode
  38. """
  39. if str(new_password).strip() != str(password_confirm).strip():
  40. click.echo(click.style("Passwords do not match.", fg="red"))
  41. return
  42. account = db.session.query(Account).filter(Account.email == email).one_or_none()
  43. if not account:
  44. click.echo(click.style("Account not found for email: {}".format(email), fg="red"))
  45. return
  46. try:
  47. valid_password(new_password)
  48. except:
  49. click.echo(click.style("Invalid password. Must match {}".format(password_pattern), fg="red"))
  50. return
  51. # generate password salt
  52. salt = secrets.token_bytes(16)
  53. base64_salt = base64.b64encode(salt).decode()
  54. # encrypt password with salt
  55. password_hashed = hash_password(new_password, salt)
  56. base64_password_hashed = base64.b64encode(password_hashed).decode()
  57. account.password = base64_password_hashed
  58. account.password_salt = base64_salt
  59. db.session.commit()
  60. click.echo(click.style("Password reset successfully.", fg="green"))
  61. @click.command("reset-email", help="Reset the account email.")
  62. @click.option("--email", prompt=True, help="Current account email")
  63. @click.option("--new-email", prompt=True, help="New email")
  64. @click.option("--email-confirm", prompt=True, help="Confirm new email")
  65. def reset_email(email, new_email, email_confirm):
  66. """
  67. Replace account email
  68. :return:
  69. """
  70. if str(new_email).strip() != str(email_confirm).strip():
  71. click.echo(click.style("New emails do not match.", fg="red"))
  72. return
  73. account = db.session.query(Account).filter(Account.email == email).one_or_none()
  74. if not account:
  75. click.echo(click.style("Account not found for email: {}".format(email), fg="red"))
  76. return
  77. try:
  78. email_validate(new_email)
  79. except:
  80. click.echo(click.style("Invalid email: {}".format(new_email), fg="red"))
  81. return
  82. account.email = new_email
  83. db.session.commit()
  84. click.echo(click.style("Email updated successfully.", fg="green"))
  85. @click.command(
  86. "reset-encrypt-key-pair",
  87. help="Reset the asymmetric key pair of workspace for encrypt LLM credentials. "
  88. "After the reset, all LLM credentials will become invalid, "
  89. "requiring re-entry."
  90. "Only support SELF_HOSTED mode.",
  91. )
  92. @click.confirmation_option(
  93. prompt=click.style(
  94. "Are you sure you want to reset encrypt key pair? This operation cannot be rolled back!", fg="red"
  95. )
  96. )
  97. def reset_encrypt_key_pair():
  98. """
  99. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  100. After the reset, all LLM credentials will become invalid, requiring re-entry.
  101. Only support SELF_HOSTED mode.
  102. """
  103. if dify_config.EDITION != "SELF_HOSTED":
  104. click.echo(click.style("This command is only for SELF_HOSTED installations.", fg="red"))
  105. return
  106. tenants = db.session.query(Tenant).all()
  107. for tenant in tenants:
  108. if not tenant:
  109. click.echo(click.style("No workspaces found. Run /install first.", fg="red"))
  110. return
  111. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  112. db.session.query(Provider).filter(Provider.provider_type == "custom", Provider.tenant_id == tenant.id).delete()
  113. db.session.query(ProviderModel).filter(ProviderModel.tenant_id == tenant.id).delete()
  114. db.session.commit()
  115. click.echo(
  116. click.style(
  117. "Congratulations! The asymmetric key pair of workspace {} has been reset.".format(tenant.id),
  118. fg="green",
  119. )
  120. )
  121. @click.command("vdb-migrate", help="Migrate vector db.")
  122. @click.option("--scope", default="all", prompt=False, help="The scope of vector database to migrate, Default is All.")
  123. def vdb_migrate(scope: str):
  124. if scope in {"knowledge", "all"}:
  125. migrate_knowledge_vector_database()
  126. if scope in {"annotation", "all"}:
  127. migrate_annotation_vector_database()
  128. def migrate_annotation_vector_database():
  129. """
  130. Migrate annotation datas to target vector database .
  131. """
  132. click.echo(click.style("Starting annotation data migration.", fg="green"))
  133. create_count = 0
  134. skipped_count = 0
  135. total_count = 0
  136. page = 1
  137. while True:
  138. try:
  139. # get apps info
  140. per_page = 50
  141. apps = (
  142. db.session.query(App)
  143. .filter(App.status == "normal")
  144. .order_by(App.created_at.desc())
  145. .limit(per_page)
  146. .offset((page - 1) * per_page)
  147. .all()
  148. )
  149. if not apps:
  150. break
  151. except NotFound:
  152. break
  153. page += 1
  154. for app in apps:
  155. total_count = total_count + 1
  156. click.echo(
  157. f"Processing the {total_count} app {app.id}. " + f"{create_count} created, {skipped_count} skipped."
  158. )
  159. try:
  160. click.echo("Creating app annotation index: {}".format(app.id))
  161. app_annotation_setting = (
  162. db.session.query(AppAnnotationSetting).filter(AppAnnotationSetting.app_id == app.id).first()
  163. )
  164. if not app_annotation_setting:
  165. skipped_count = skipped_count + 1
  166. click.echo("App annotation setting disabled: {}".format(app.id))
  167. continue
  168. # get dataset_collection_binding info
  169. dataset_collection_binding = (
  170. db.session.query(DatasetCollectionBinding)
  171. .filter(DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id)
  172. .first()
  173. )
  174. if not dataset_collection_binding:
  175. click.echo("App annotation collection binding not found: {}".format(app.id))
  176. continue
  177. annotations = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app.id).all()
  178. dataset = Dataset(
  179. id=app.id,
  180. tenant_id=app.tenant_id,
  181. indexing_technique="high_quality",
  182. embedding_model_provider=dataset_collection_binding.provider_name,
  183. embedding_model=dataset_collection_binding.model_name,
  184. collection_binding_id=dataset_collection_binding.id,
  185. )
  186. documents = []
  187. if annotations:
  188. for annotation in annotations:
  189. document = Document(
  190. page_content=annotation.question,
  191. metadata={"annotation_id": annotation.id, "app_id": app.id, "doc_id": annotation.id},
  192. )
  193. documents.append(document)
  194. vector = Vector(dataset, attributes=["doc_id", "annotation_id", "app_id"])
  195. click.echo(f"Migrating annotations for app: {app.id}.")
  196. try:
  197. vector.delete()
  198. click.echo(click.style(f"Deleted vector index for app {app.id}.", fg="green"))
  199. except Exception as e:
  200. click.echo(click.style(f"Failed to delete vector index for app {app.id}.", fg="red"))
  201. raise e
  202. if documents:
  203. try:
  204. click.echo(
  205. click.style(
  206. f"Creating vector index with {len(documents)} annotations for app {app.id}.",
  207. fg="green",
  208. )
  209. )
  210. vector.create(documents)
  211. click.echo(click.style(f"Created vector index for app {app.id}.", fg="green"))
  212. except Exception as e:
  213. click.echo(click.style(f"Failed to created vector index for app {app.id}.", fg="red"))
  214. raise e
  215. click.echo(f"Successfully migrated app annotation {app.id}.")
  216. create_count += 1
  217. except Exception as e:
  218. click.echo(
  219. click.style(
  220. "Error creating app annotation index: {} {}".format(e.__class__.__name__, str(e)), fg="red"
  221. )
  222. )
  223. continue
  224. click.echo(
  225. click.style(
  226. f"Migration complete. Created {create_count} app annotation indexes. Skipped {skipped_count} apps.",
  227. fg="green",
  228. )
  229. )
  230. def migrate_knowledge_vector_database():
  231. """
  232. Migrate vector database datas to target vector database .
  233. """
  234. click.echo(click.style("Starting vector database migration.", fg="green"))
  235. create_count = 0
  236. skipped_count = 0
  237. total_count = 0
  238. vector_type = dify_config.VECTOR_STORE
  239. upper_collection_vector_types = {
  240. VectorType.MILVUS,
  241. VectorType.PGVECTOR,
  242. VectorType.RELYT,
  243. VectorType.WEAVIATE,
  244. VectorType.ORACLE,
  245. VectorType.ELASTICSEARCH,
  246. VectorType.OPENGAUSS,
  247. }
  248. lower_collection_vector_types = {
  249. VectorType.ANALYTICDB,
  250. VectorType.CHROMA,
  251. VectorType.MYSCALE,
  252. VectorType.PGVECTO_RS,
  253. VectorType.TIDB_VECTOR,
  254. VectorType.OPENSEARCH,
  255. VectorType.TENCENT,
  256. VectorType.BAIDU,
  257. VectorType.VIKINGDB,
  258. VectorType.UPSTASH,
  259. VectorType.COUCHBASE,
  260. VectorType.OCEANBASE,
  261. }
  262. page = 1
  263. while True:
  264. try:
  265. datasets = (
  266. Dataset.query.filter(Dataset.indexing_technique == "high_quality")
  267. .order_by(Dataset.created_at.desc())
  268. .paginate(page=page, per_page=50)
  269. )
  270. except NotFound:
  271. break
  272. page += 1
  273. for dataset in datasets:
  274. total_count = total_count + 1
  275. click.echo(
  276. f"Processing the {total_count} dataset {dataset.id}. {create_count} created, {skipped_count} skipped."
  277. )
  278. try:
  279. click.echo("Creating dataset vector database index: {}".format(dataset.id))
  280. if dataset.index_struct_dict:
  281. if dataset.index_struct_dict["type"] == vector_type:
  282. skipped_count = skipped_count + 1
  283. continue
  284. collection_name = ""
  285. dataset_id = dataset.id
  286. if vector_type in upper_collection_vector_types:
  287. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  288. elif vector_type == VectorType.QDRANT:
  289. if dataset.collection_binding_id:
  290. dataset_collection_binding = (
  291. db.session.query(DatasetCollectionBinding)
  292. .filter(DatasetCollectionBinding.id == dataset.collection_binding_id)
  293. .one_or_none()
  294. )
  295. if dataset_collection_binding:
  296. collection_name = dataset_collection_binding.collection_name
  297. else:
  298. raise ValueError("Dataset Collection Binding not found")
  299. else:
  300. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  301. elif vector_type in lower_collection_vector_types:
  302. collection_name = Dataset.gen_collection_name_by_id(dataset_id).lower()
  303. else:
  304. raise ValueError(f"Vector store {vector_type} is not supported.")
  305. index_struct_dict = {"type": vector_type, "vector_store": {"class_prefix": collection_name}}
  306. dataset.index_struct = json.dumps(index_struct_dict)
  307. vector = Vector(dataset)
  308. click.echo(f"Migrating dataset {dataset.id}.")
  309. try:
  310. vector.delete()
  311. click.echo(
  312. click.style(f"Deleted vector index {collection_name} for dataset {dataset.id}.", fg="green")
  313. )
  314. except Exception as e:
  315. click.echo(
  316. click.style(
  317. f"Failed to delete vector index {collection_name} for dataset {dataset.id}.", fg="red"
  318. )
  319. )
  320. raise e
  321. dataset_documents = (
  322. db.session.query(DatasetDocument)
  323. .filter(
  324. DatasetDocument.dataset_id == dataset.id,
  325. DatasetDocument.indexing_status == "completed",
  326. DatasetDocument.enabled == True,
  327. DatasetDocument.archived == False,
  328. )
  329. .all()
  330. )
  331. documents = []
  332. segments_count = 0
  333. for dataset_document in dataset_documents:
  334. segments = (
  335. db.session.query(DocumentSegment)
  336. .filter(
  337. DocumentSegment.document_id == dataset_document.id,
  338. DocumentSegment.status == "completed",
  339. DocumentSegment.enabled == True,
  340. )
  341. .all()
  342. )
  343. for segment in segments:
  344. document = Document(
  345. page_content=segment.content,
  346. metadata={
  347. "doc_id": segment.index_node_id,
  348. "doc_hash": segment.index_node_hash,
  349. "document_id": segment.document_id,
  350. "dataset_id": segment.dataset_id,
  351. },
  352. )
  353. documents.append(document)
  354. segments_count = segments_count + 1
  355. if documents:
  356. try:
  357. click.echo(
  358. click.style(
  359. f"Creating vector index with {len(documents)} documents of {segments_count}"
  360. f" segments for dataset {dataset.id}.",
  361. fg="green",
  362. )
  363. )
  364. vector.create(documents)
  365. click.echo(click.style(f"Created vector index for dataset {dataset.id}.", fg="green"))
  366. except Exception as e:
  367. click.echo(click.style(f"Failed to created vector index for dataset {dataset.id}.", fg="red"))
  368. raise e
  369. db.session.add(dataset)
  370. db.session.commit()
  371. click.echo(f"Successfully migrated dataset {dataset.id}.")
  372. create_count += 1
  373. except Exception as e:
  374. db.session.rollback()
  375. click.echo(
  376. click.style("Error creating dataset index: {} {}".format(e.__class__.__name__, str(e)), fg="red")
  377. )
  378. continue
  379. click.echo(
  380. click.style(
  381. f"Migration complete. Created {create_count} dataset indexes. Skipped {skipped_count} datasets.", fg="green"
  382. )
  383. )
  384. @click.command("convert-to-agent-apps", help="Convert Agent Assistant to Agent App.")
  385. def convert_to_agent_apps():
  386. """
  387. Convert Agent Assistant to Agent App.
  388. """
  389. click.echo(click.style("Starting convert to agent apps.", fg="green"))
  390. proceeded_app_ids = []
  391. while True:
  392. # fetch first 1000 apps
  393. sql_query = """SELECT a.id AS id FROM apps a
  394. INNER JOIN app_model_configs am ON a.app_model_config_id=am.id
  395. WHERE a.mode = 'chat'
  396. AND am.agent_mode is not null
  397. AND (
  398. am.agent_mode like '%"strategy": "function_call"%'
  399. OR am.agent_mode like '%"strategy": "react"%'
  400. )
  401. AND (
  402. am.agent_mode like '{"enabled": true%'
  403. OR am.agent_mode like '{"max_iteration": %'
  404. ) ORDER BY a.created_at DESC LIMIT 1000
  405. """
  406. with db.engine.begin() as conn:
  407. rs = conn.execute(db.text(sql_query))
  408. apps = []
  409. for i in rs:
  410. app_id = str(i.id)
  411. if app_id not in proceeded_app_ids:
  412. proceeded_app_ids.append(app_id)
  413. app = db.session.query(App).filter(App.id == app_id).first()
  414. if app is not None:
  415. apps.append(app)
  416. if len(apps) == 0:
  417. break
  418. for app in apps:
  419. click.echo("Converting app: {}".format(app.id))
  420. try:
  421. app.mode = AppMode.AGENT_CHAT.value
  422. db.session.commit()
  423. # update conversation mode to agent
  424. db.session.query(Conversation).filter(Conversation.app_id == app.id).update(
  425. {Conversation.mode: AppMode.AGENT_CHAT.value}
  426. )
  427. db.session.commit()
  428. click.echo(click.style("Converted app: {}".format(app.id), fg="green"))
  429. except Exception as e:
  430. click.echo(click.style("Convert app error: {} {}".format(e.__class__.__name__, str(e)), fg="red"))
  431. click.echo(click.style("Conversion complete. Converted {} agent apps.".format(len(proceeded_app_ids)), fg="green"))
  432. @click.command("add-qdrant-index", help="Add Qdrant index.")
  433. @click.option("--field", default="metadata.doc_id", prompt=False, help="Index field , default is metadata.doc_id.")
  434. def add_qdrant_index(field: str):
  435. click.echo(click.style("Starting Qdrant index creation.", fg="green"))
  436. create_count = 0
  437. try:
  438. bindings = db.session.query(DatasetCollectionBinding).all()
  439. if not bindings:
  440. click.echo(click.style("No dataset collection bindings found.", fg="red"))
  441. return
  442. import qdrant_client
  443. from qdrant_client.http.exceptions import UnexpectedResponse
  444. from qdrant_client.http.models import PayloadSchemaType
  445. from core.rag.datasource.vdb.qdrant.qdrant_vector import QdrantConfig
  446. for binding in bindings:
  447. if dify_config.QDRANT_URL is None:
  448. raise ValueError("Qdrant URL is required.")
  449. qdrant_config = QdrantConfig(
  450. endpoint=dify_config.QDRANT_URL,
  451. api_key=dify_config.QDRANT_API_KEY,
  452. root_path=current_app.root_path,
  453. timeout=dify_config.QDRANT_CLIENT_TIMEOUT,
  454. grpc_port=dify_config.QDRANT_GRPC_PORT,
  455. prefer_grpc=dify_config.QDRANT_GRPC_ENABLED,
  456. )
  457. try:
  458. client = qdrant_client.QdrantClient(**qdrant_config.to_qdrant_params())
  459. # create payload index
  460. client.create_payload_index(binding.collection_name, field, field_schema=PayloadSchemaType.KEYWORD)
  461. create_count += 1
  462. except UnexpectedResponse as e:
  463. # Collection does not exist, so return
  464. if e.status_code == 404:
  465. click.echo(click.style(f"Collection not found: {binding.collection_name}.", fg="red"))
  466. continue
  467. # Some other error occurred, so re-raise the exception
  468. else:
  469. click.echo(
  470. click.style(
  471. f"Failed to create Qdrant index for collection: {binding.collection_name}.", fg="red"
  472. )
  473. )
  474. except Exception:
  475. click.echo(click.style("Failed to create Qdrant client.", fg="red"))
  476. click.echo(click.style(f"Index creation complete. Created {create_count} collection indexes.", fg="green"))
  477. @click.command("old-metadata-migration", help="Old metadata migration.")
  478. def old_metadata_migration():
  479. """
  480. Old metadata migration.
  481. """
  482. click.echo(click.style("Starting old metadata migration.", fg="green"))
  483. page = 1
  484. while True:
  485. try:
  486. documents = (
  487. DatasetDocument.query.filter(DatasetDocument.doc_metadata is not None)
  488. .order_by(DatasetDocument.created_at.desc())
  489. .paginate(page=page, per_page=50)
  490. )
  491. except NotFound:
  492. break
  493. if not documents:
  494. break
  495. for document in documents:
  496. if document.doc_metadata:
  497. doc_metadata = document.doc_metadata
  498. for key, value in doc_metadata.items():
  499. for field in BuiltInField:
  500. if field.value == key:
  501. break
  502. else:
  503. dataset_metadata = (
  504. db.session.query(DatasetMetadata)
  505. .filter(DatasetMetadata.dataset_id == document.dataset_id, DatasetMetadata.name == key)
  506. .first()
  507. )
  508. if not dataset_metadata:
  509. dataset_metadata = DatasetMetadata(
  510. tenant_id=document.tenant_id,
  511. dataset_id=document.dataset_id,
  512. name=key,
  513. type="string",
  514. created_by=document.created_by,
  515. )
  516. db.session.add(dataset_metadata)
  517. db.session.flush()
  518. dataset_metadata_binding = DatasetMetadataBinding(
  519. tenant_id=document.tenant_id,
  520. dataset_id=document.dataset_id,
  521. metadata_id=dataset_metadata.id,
  522. document_id=document.id,
  523. created_by=document.created_by,
  524. )
  525. db.session.add(dataset_metadata_binding)
  526. else:
  527. dataset_metadata_binding = DatasetMetadataBinding.query.filter(
  528. DatasetMetadataBinding.dataset_id == document.dataset_id,
  529. DatasetMetadataBinding.document_id == document.id,
  530. DatasetMetadataBinding.metadata_id == dataset_metadata.id,
  531. ).first()
  532. if not dataset_metadata_binding:
  533. dataset_metadata_binding = DatasetMetadataBinding(
  534. tenant_id=document.tenant_id,
  535. dataset_id=document.dataset_id,
  536. metadata_id=dataset_metadata.id,
  537. document_id=document.id,
  538. created_by=document.created_by,
  539. )
  540. db.session.add(dataset_metadata_binding)
  541. db.session.commit()
  542. page += 1
  543. click.echo(click.style("Old metadata migration completed.", fg="green"))
  544. @click.command("create-tenant", help="Create account and tenant.")
  545. @click.option("--email", prompt=True, help="Tenant account email.")
  546. @click.option("--name", prompt=True, help="Workspace name.")
  547. @click.option("--language", prompt=True, help="Account language, default: en-US.")
  548. def create_tenant(email: str, language: Optional[str] = None, name: Optional[str] = None):
  549. """
  550. Create tenant account
  551. """
  552. if not email:
  553. click.echo(click.style("Email is required.", fg="red"))
  554. return
  555. # Create account
  556. email = email.strip()
  557. if "@" not in email:
  558. click.echo(click.style("Invalid email address.", fg="red"))
  559. return
  560. account_name = email.split("@")[0]
  561. if language not in languages:
  562. language = "en-US"
  563. # Validates name encoding for non-Latin characters.
  564. name = name.strip().encode("utf-8").decode("utf-8") if name else None
  565. # generate random password
  566. new_password = secrets.token_urlsafe(16)
  567. # register account
  568. account = RegisterService.register(
  569. email=email,
  570. name=account_name,
  571. password=new_password,
  572. language=language,
  573. create_workspace_required=False,
  574. )
  575. TenantService.create_owner_tenant_if_not_exist(account, name)
  576. click.echo(
  577. click.style(
  578. "Account and tenant created.\nAccount: {}\nPassword: {}".format(email, new_password),
  579. fg="green",
  580. )
  581. )
  582. @click.command("upgrade-db", help="Upgrade the database")
  583. def upgrade_db():
  584. click.echo("Preparing database migration...")
  585. lock = redis_client.lock(name="db_upgrade_lock", timeout=60)
  586. if lock.acquire(blocking=False):
  587. try:
  588. click.echo(click.style("Starting database migration.", fg="green"))
  589. # run db migration
  590. import flask_migrate # type: ignore
  591. flask_migrate.upgrade()
  592. click.echo(click.style("Database migration successful!", fg="green"))
  593. except Exception:
  594. logging.exception("Failed to execute database migration")
  595. finally:
  596. lock.release()
  597. else:
  598. click.echo("Database migration skipped")
  599. @click.command("fix-app-site-missing", help="Fix app related site missing issue.")
  600. def fix_app_site_missing():
  601. """
  602. Fix app related site missing issue.
  603. """
  604. click.echo(click.style("Starting fix for missing app-related sites.", fg="green"))
  605. failed_app_ids = []
  606. while True:
  607. sql = """select apps.id as id from apps left join sites on sites.app_id=apps.id
  608. where sites.id is null limit 1000"""
  609. with db.engine.begin() as conn:
  610. rs = conn.execute(db.text(sql))
  611. processed_count = 0
  612. for i in rs:
  613. processed_count += 1
  614. app_id = str(i.id)
  615. if app_id in failed_app_ids:
  616. continue
  617. try:
  618. app = db.session.query(App).filter(App.id == app_id).first()
  619. if not app:
  620. print(f"App {app_id} not found")
  621. continue
  622. tenant = app.tenant
  623. if tenant:
  624. accounts = tenant.get_accounts()
  625. if not accounts:
  626. print("Fix failed for app {}".format(app.id))
  627. continue
  628. account = accounts[0]
  629. print("Fixing missing site for app {}".format(app.id))
  630. app_was_created.send(app, account=account)
  631. except Exception:
  632. failed_app_ids.append(app_id)
  633. click.echo(click.style("Failed to fix missing site for app {}".format(app_id), fg="red"))
  634. logging.exception(f"Failed to fix app related site missing issue, app_id: {app_id}")
  635. continue
  636. if not processed_count:
  637. break
  638. click.echo(click.style("Fix for missing app-related sites completed successfully!", fg="green"))
  639. @click.command("migrate-data-for-plugin", help="Migrate data for plugin.")
  640. def migrate_data_for_plugin():
  641. """
  642. Migrate data for plugin.
  643. """
  644. click.echo(click.style("Starting migrate data for plugin.", fg="white"))
  645. PluginDataMigration.migrate()
  646. click.echo(click.style("Migrate data for plugin completed.", fg="green"))
  647. @click.command("extract-plugins", help="Extract plugins.")
  648. @click.option("--output_file", prompt=True, help="The file to store the extracted plugins.", default="plugins.jsonl")
  649. @click.option("--workers", prompt=True, help="The number of workers to extract plugins.", default=10)
  650. def extract_plugins(output_file: str, workers: int):
  651. """
  652. Extract plugins.
  653. """
  654. click.echo(click.style("Starting extract plugins.", fg="white"))
  655. PluginMigration.extract_plugins(output_file, workers)
  656. click.echo(click.style("Extract plugins completed.", fg="green"))
  657. @click.command("extract-unique-identifiers", help="Extract unique identifiers.")
  658. @click.option(
  659. "--output_file",
  660. prompt=True,
  661. help="The file to store the extracted unique identifiers.",
  662. default="unique_identifiers.json",
  663. )
  664. @click.option(
  665. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  666. )
  667. def extract_unique_plugins(output_file: str, input_file: str):
  668. """
  669. Extract unique plugins.
  670. """
  671. click.echo(click.style("Starting extract unique plugins.", fg="white"))
  672. PluginMigration.extract_unique_plugins_to_file(input_file, output_file)
  673. click.echo(click.style("Extract unique plugins completed.", fg="green"))
  674. @click.command("install-plugins", help="Install plugins.")
  675. @click.option(
  676. "--input_file", prompt=True, help="The file to store the extracted unique identifiers.", default="plugins.jsonl"
  677. )
  678. @click.option(
  679. "--output_file", prompt=True, help="The file to store the installed plugins.", default="installed_plugins.jsonl"
  680. )
  681. @click.option("--workers", prompt=True, help="The number of workers to install plugins.", default=100)
  682. def install_plugins(input_file: str, output_file: str, workers: int):
  683. """
  684. Install plugins.
  685. """
  686. click.echo(click.style("Starting install plugins.", fg="white"))
  687. PluginMigration.install_plugins(input_file, output_file, workers)
  688. click.echo(click.style("Install plugins completed.", fg="green"))
  689. @click.command("clear-free-plan-tenant-expired-logs", help="Clear free plan tenant expired logs.")
  690. @click.option("--days", prompt=True, help="The days to clear free plan tenant expired logs.", default=30)
  691. @click.option("--batch", prompt=True, help="The batch size to clear free plan tenant expired logs.", default=100)
  692. @click.option(
  693. "--tenant_ids",
  694. prompt=True,
  695. multiple=True,
  696. help="The tenant ids to clear free plan tenant expired logs.",
  697. )
  698. def clear_free_plan_tenant_expired_logs(days: int, batch: int, tenant_ids: list[str]):
  699. """
  700. Clear free plan tenant expired logs.
  701. """
  702. click.echo(click.style("Starting clear free plan tenant expired logs.", fg="white"))
  703. ClearFreePlanTenantExpiredLogs.process(days, batch, tenant_ids)
  704. click.echo(click.style("Clear free plan tenant expired logs completed.", fg="green"))