commands.py 27 KB

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