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

commands.py 76KB

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