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

683 line
19 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: MIT. See LICENSE
  3. import json
  4. import os
  5. import sys
  6. from collections import OrderedDict
  7. from typing import List, Dict
  8. import frappe
  9. from frappe.defaults import _clear_cache
  10. def _new_site(
  11. db_name,
  12. site,
  13. db_root_username=None,
  14. db_root_password=None,
  15. admin_password=None,
  16. verbose=False,
  17. install_apps=None,
  18. source_sql=None,
  19. force=False,
  20. no_mariadb_socket=False,
  21. reinstall=False,
  22. db_password=None,
  23. db_type=None,
  24. db_host=None,
  25. db_port=None,
  26. new_site=False,
  27. ):
  28. """Install a new Frappe site"""
  29. from frappe.commands.scheduler import _is_scheduler_enabled
  30. from frappe.utils import get_site_path, scheduler, touch_file
  31. if not force and os.path.exists(site):
  32. print("Site {0} already exists".format(site))
  33. sys.exit(1)
  34. if no_mariadb_socket and not db_type == "mariadb":
  35. print("--no-mariadb-socket requires db_type to be set to mariadb.")
  36. sys.exit(1)
  37. frappe.init(site=site)
  38. if not db_name:
  39. import hashlib
  40. db_name = "_" + hashlib.sha1(os.path.realpath(frappe.get_site_path()).encode()).hexdigest()[:16]
  41. try:
  42. # enable scheduler post install?
  43. enable_scheduler = _is_scheduler_enabled()
  44. except Exception:
  45. enable_scheduler = False
  46. make_site_dirs()
  47. installing = touch_file(get_site_path("locks", "installing.lock"))
  48. install_db(
  49. root_login=db_root_username,
  50. root_password=db_root_password,
  51. db_name=db_name,
  52. admin_password=admin_password,
  53. verbose=verbose,
  54. source_sql=source_sql,
  55. force=force,
  56. reinstall=reinstall,
  57. db_password=db_password,
  58. db_type=db_type,
  59. db_host=db_host,
  60. db_port=db_port,
  61. no_mariadb_socket=no_mariadb_socket,
  62. )
  63. apps_to_install = (
  64. ["frappe"] + (frappe.conf.get("install_apps") or []) + (list(install_apps) or [])
  65. )
  66. for app in apps_to_install:
  67. install_app(app, verbose=verbose, set_as_patched=not source_sql)
  68. os.remove(installing)
  69. scheduler.toggle_scheduler(enable_scheduler)
  70. frappe.db.commit()
  71. scheduler_status = (
  72. "disabled" if frappe.utils.scheduler.is_scheduler_disabled() else "enabled"
  73. )
  74. print("*** Scheduler is", scheduler_status, "***")
  75. def install_db(root_login=None, root_password=None, db_name=None, source_sql=None,
  76. admin_password=None, verbose=True, force=0, site_config=None, reinstall=False,
  77. db_password=None, db_type=None, db_host=None, db_port=None, no_mariadb_socket=False):
  78. import frappe.database
  79. from frappe.database import setup_database
  80. if not db_type:
  81. db_type = frappe.conf.db_type or 'mariadb'
  82. if not root_login and db_type == 'mariadb':
  83. root_login='root'
  84. elif not root_login and db_type == 'postgres':
  85. root_login='postgres'
  86. make_conf(db_name, site_config=site_config, db_password=db_password, db_type=db_type, db_host=db_host, db_port=db_port)
  87. frappe.flags.in_install_db = True
  88. frappe.flags.root_login = root_login
  89. frappe.flags.root_password = root_password
  90. setup_database(force, source_sql, verbose, no_mariadb_socket)
  91. frappe.conf.admin_password = frappe.conf.admin_password or admin_password
  92. remove_missing_apps()
  93. frappe.db.create_auth_table()
  94. frappe.db.create_global_search_table()
  95. frappe.db.create_user_settings_table()
  96. frappe.flags.in_install_db = False
  97. def install_app(name, verbose=False, set_as_patched=True):
  98. from frappe.core.doctype.scheduled_job_type.scheduled_job_type import sync_jobs
  99. from frappe.model.sync import sync_for
  100. from frappe.modules.utils import sync_customizations
  101. from frappe.utils.fixtures import sync_fixtures
  102. frappe.flags.in_install = name
  103. frappe.flags.ignore_in_install = False
  104. frappe.clear_cache()
  105. app_hooks = frappe.get_hooks(app_name=name)
  106. installed_apps = frappe.get_installed_apps()
  107. # install pre-requisites
  108. if app_hooks.required_apps:
  109. for app in app_hooks.required_apps:
  110. install_app(app, verbose=verbose)
  111. frappe.flags.in_install = name
  112. frappe.clear_cache()
  113. if name not in frappe.get_all_apps():
  114. raise Exception("App not in apps.txt")
  115. if name in installed_apps:
  116. frappe.msgprint(frappe._("App {0} already installed").format(name))
  117. return
  118. print("\nInstalling {0}...".format(name))
  119. if name != "frappe":
  120. frappe.only_for("System Manager")
  121. for before_install in app_hooks.before_install or []:
  122. out = frappe.get_attr(before_install)()
  123. if out is False:
  124. return
  125. if name != "frappe":
  126. add_module_defs(name)
  127. sync_for(name, force=True, reset_permissions=True)
  128. add_to_installed_apps(name)
  129. frappe.get_doc('Portal Settings', 'Portal Settings').sync_menu()
  130. if set_as_patched:
  131. set_all_patches_as_completed(name)
  132. for after_install in app_hooks.after_install or []:
  133. frappe.get_attr(after_install)()
  134. sync_jobs()
  135. sync_fixtures(name)
  136. sync_customizations(name)
  137. for after_sync in app_hooks.after_sync or []:
  138. frappe.get_attr(after_sync)() #
  139. frappe.flags.in_install = False
  140. def add_to_installed_apps(app_name, rebuild_website=True):
  141. installed_apps = frappe.get_installed_apps()
  142. if app_name not in installed_apps:
  143. installed_apps.append(app_name)
  144. frappe.db.set_global("installed_apps", json.dumps(installed_apps))
  145. frappe.db.commit()
  146. if frappe.flags.in_install:
  147. post_install(rebuild_website)
  148. def remove_from_installed_apps(app_name):
  149. installed_apps = frappe.get_installed_apps()
  150. if app_name in installed_apps:
  151. installed_apps.remove(app_name)
  152. frappe.db.set_value("DefaultValue", {"defkey": "installed_apps"}, "defvalue", json.dumps(installed_apps))
  153. _clear_cache("__global")
  154. frappe.db.commit()
  155. if frappe.flags.in_install:
  156. post_install()
  157. def remove_app(app_name, dry_run=False, yes=False, no_backup=False, force=False):
  158. """Remove app and all linked to the app's module with the app from a site."""
  159. import click
  160. site = frappe.local.site
  161. app_hooks = frappe.get_hooks(app_name=app_name)
  162. # dont allow uninstall app if not installed unless forced
  163. if not force:
  164. if app_name not in frappe.get_installed_apps():
  165. click.secho(f"App {app_name} not installed on Site {site}", fg="yellow")
  166. return
  167. print(f"Uninstalling App {app_name} from Site {site}...")
  168. if not dry_run and not yes:
  169. confirm = click.confirm(
  170. "All doctypes (including custom), modules related to this app will be"
  171. " deleted. Are you sure you want to continue?"
  172. )
  173. if not confirm:
  174. return
  175. if not (dry_run or no_backup):
  176. from frappe.utils.backups import scheduled_backup
  177. print("Backing up...")
  178. scheduled_backup(ignore_files=True)
  179. frappe.flags.in_uninstall = True
  180. for before_uninstall in app_hooks.before_uninstall or []:
  181. frappe.get_attr(before_uninstall)()
  182. modules = frappe.get_all("Module Def", filters={"app_name": app_name}, pluck="name")
  183. drop_doctypes = _delete_modules(modules, dry_run=dry_run)
  184. _delete_doctypes(drop_doctypes, dry_run=dry_run)
  185. if not dry_run:
  186. remove_from_installed_apps(app_name)
  187. frappe.get_single('Installed Applications').update_versions()
  188. frappe.db.commit()
  189. for after_uninstall in app_hooks.after_uninstall or []:
  190. frappe.get_attr(after_uninstall)()
  191. click.secho(f"Uninstalled App {app_name} from Site {site}", fg="green")
  192. frappe.flags.in_uninstall = False
  193. def _delete_modules(modules: List[str], dry_run: bool) -> List[str]:
  194. """ Delete modules belonging to the app and all related doctypes.
  195. Note: All record linked linked to Module Def are also deleted.
  196. Returns: list of deleted doctypes."""
  197. drop_doctypes = []
  198. doctype_link_field_map = _get_module_linked_doctype_field_map()
  199. for module_name in modules:
  200. print(f"Deleting Module '{module_name}'")
  201. for doctype in frappe.get_all(
  202. "DocType", filters={"module": module_name}, fields=["name", "issingle"]
  203. ):
  204. print(f"* removing DocType '{doctype.name}'...")
  205. if not dry_run:
  206. if doctype.issingle:
  207. frappe.delete_doc("DocType", doctype.name, ignore_on_trash=True)
  208. else:
  209. drop_doctypes.append(doctype.name)
  210. _delete_linked_documents(module_name, doctype_link_field_map, dry_run=dry_run)
  211. print(f"* removing Module Def '{module_name}'...")
  212. if not dry_run:
  213. frappe.delete_doc("Module Def", module_name, ignore_on_trash=True, force=True)
  214. return drop_doctypes
  215. def _delete_linked_documents(
  216. module_name: str,
  217. doctype_linkfield_map: Dict[str, str],
  218. dry_run: bool
  219. ) -> None:
  220. """Deleted all records linked with module def"""
  221. for doctype, fieldname in doctype_linkfield_map.items():
  222. for record in frappe.get_all(doctype, filters={fieldname: module_name}, pluck="name"):
  223. print(f"* removing {doctype} '{record}'...")
  224. if not dry_run:
  225. frappe.delete_doc(doctype, record, ignore_on_trash=True, force=True)
  226. def _get_module_linked_doctype_field_map() -> Dict[str, str]:
  227. """ Get all the doctypes which have module linked with them.
  228. returns ordered dictionary with doctype->link field mapping."""
  229. # Hardcoded to change order of deletion
  230. ordered_doctypes = [
  231. ("Workspace", "module"),
  232. ("Report", "module"),
  233. ("Page", "module"),
  234. ("Web Form", "module")
  235. ]
  236. doctype_to_field_map = OrderedDict(ordered_doctypes)
  237. linked_doctypes = frappe.get_all(
  238. "DocField", filters={"fieldtype": "Link", "options": "Module Def"}, fields=["parent", "fieldname"]
  239. )
  240. existing_linked_doctypes = [d for d in linked_doctypes if frappe.db.exists("DocType", d.parent)]
  241. for d in existing_linked_doctypes:
  242. # DocType deletion is handled separately in the end
  243. if d.parent not in doctype_to_field_map and d.parent != "DocType":
  244. doctype_to_field_map[d.parent] = d.fieldname
  245. return doctype_to_field_map
  246. def _delete_doctypes(doctypes: List[str], dry_run: bool) -> None:
  247. for doctype in set(doctypes):
  248. print(f"* dropping Table for '{doctype}'...")
  249. if not dry_run:
  250. frappe.delete_doc("DocType", doctype, ignore_on_trash=True)
  251. frappe.db.sql_ddl(f"DROP TABLE IF EXISTS `tab{doctype}`")
  252. def post_install(rebuild_website=False):
  253. from frappe.website.utils import clear_website_cache
  254. if rebuild_website:
  255. clear_website_cache()
  256. init_singles()
  257. frappe.db.commit()
  258. frappe.clear_cache()
  259. def set_all_patches_as_completed(app):
  260. from frappe.modules.patch_handler import get_patches_from_app
  261. patches = get_patches_from_app(app)
  262. for patch in patches:
  263. frappe.get_doc({
  264. "doctype": "Patch Log",
  265. "patch": patch
  266. }).insert(ignore_permissions=True)
  267. frappe.db.commit()
  268. def init_singles():
  269. singles = [single['name'] for single in frappe.get_all("DocType", filters={'issingle': True})]
  270. for single in singles:
  271. if not frappe.db.get_singles_dict(single):
  272. doc = frappe.new_doc(single)
  273. doc.flags.ignore_mandatory=True
  274. doc.flags.ignore_validate=True
  275. doc.save()
  276. def make_conf(db_name=None, db_password=None, site_config=None, db_type=None, db_host=None, db_port=None):
  277. site = frappe.local.site
  278. make_site_config(db_name, db_password, site_config, db_type=db_type, db_host=db_host, db_port=db_port)
  279. sites_path = frappe.local.sites_path
  280. frappe.destroy()
  281. frappe.init(site, sites_path=sites_path)
  282. def make_site_config(db_name=None, db_password=None, site_config=None, db_type=None, db_host=None, db_port=None):
  283. frappe.create_folder(os.path.join(frappe.local.site_path))
  284. site_file = get_site_config_path()
  285. if not os.path.exists(site_file):
  286. if not (site_config and isinstance(site_config, dict)):
  287. site_config = get_conf_params(db_name, db_password)
  288. if db_type:
  289. site_config['db_type'] = db_type
  290. if db_host:
  291. site_config['db_host'] = db_host
  292. if db_port:
  293. site_config['db_port'] = db_port
  294. with open(site_file, "w") as f:
  295. f.write(json.dumps(site_config, indent=1, sort_keys=True))
  296. def update_site_config(key, value, validate=True, site_config_path=None):
  297. """Update a value in site_config"""
  298. if not site_config_path:
  299. site_config_path = get_site_config_path()
  300. with open(site_config_path, "r") as f:
  301. site_config = json.loads(f.read())
  302. # In case of non-int value
  303. if value in ('0', '1'):
  304. value = int(value)
  305. # boolean
  306. if value == 'false': value = False
  307. if value == 'true': value = True
  308. # remove key if value is None
  309. if value == "None":
  310. if key in site_config:
  311. del site_config[key]
  312. else:
  313. site_config[key] = value
  314. with open(site_config_path, "w") as f:
  315. f.write(json.dumps(site_config, indent=1, sort_keys=True))
  316. if hasattr(frappe.local, "conf"):
  317. frappe.local.conf[key] = value
  318. def get_site_config_path():
  319. return os.path.join(frappe.local.site_path, "site_config.json")
  320. def get_conf_params(db_name=None, db_password=None):
  321. if not db_name:
  322. db_name = input("Database Name: ")
  323. if not db_name:
  324. raise Exception("Database Name Required")
  325. if not db_password:
  326. from frappe.utils import random_string
  327. db_password = random_string(16)
  328. return {"db_name": db_name, "db_password": db_password}
  329. def make_site_dirs():
  330. for dir_path in [
  331. os.path.join("public", "files"),
  332. os.path.join("private", "backups"),
  333. os.path.join("private", "files"),
  334. "error-snapshots",
  335. "locks",
  336. "logs",
  337. ]:
  338. path = frappe.get_site_path(dir_path)
  339. os.makedirs(path, exist_ok=True)
  340. def add_module_defs(app):
  341. modules = frappe.get_module_list(app)
  342. for module in modules:
  343. d = frappe.new_doc("Module Def")
  344. d.app_name = app
  345. d.module_name = module
  346. d.save(ignore_permissions=True)
  347. def remove_missing_apps():
  348. import importlib
  349. apps = ('frappe_subscription', 'shopping_cart')
  350. installed_apps = json.loads(frappe.db.get_global("installed_apps") or "[]")
  351. for app in apps:
  352. if app in installed_apps:
  353. try:
  354. importlib.import_module(app)
  355. except ImportError:
  356. installed_apps.remove(app)
  357. frappe.db.set_global("installed_apps", json.dumps(installed_apps))
  358. def extract_sql_from_archive(sql_file_path):
  359. """Return the path of an SQL file if the passed argument is the path of a gzipped
  360. SQL file or an SQL file path. The path may be absolute or relative from the bench
  361. root directory or the sites sub-directory.
  362. Args:
  363. sql_file_path (str): Path of the SQL file
  364. Returns:
  365. str: Path of the decompressed SQL file
  366. """
  367. from frappe.utils import get_bench_relative_path
  368. sql_file_path = get_bench_relative_path(sql_file_path)
  369. # Extract the gzip file if user has passed *.sql.gz file instead of *.sql file
  370. if sql_file_path.endswith('sql.gz'):
  371. decompressed_file_name = extract_sql_gzip(sql_file_path)
  372. else:
  373. decompressed_file_name = sql_file_path
  374. # convert archive sql to latest compatible
  375. convert_archive_content(decompressed_file_name)
  376. return decompressed_file_name
  377. def convert_archive_content(sql_file_path):
  378. if frappe.conf.db_type == "mariadb":
  379. # ever since mariaDB 10.6, row_format COMPRESSED has been deprecated and removed
  380. # this step is added to ease restoring sites depending on older mariaDB servers
  381. from frappe.utils import random_string
  382. from pathlib import Path
  383. old_sql_file_path = Path(f"{sql_file_path}_{random_string(10)}")
  384. sql_file_path = Path(sql_file_path)
  385. os.rename(sql_file_path, old_sql_file_path)
  386. sql_file_path.touch()
  387. with open(old_sql_file_path) as r, open(sql_file_path, "a") as w:
  388. for line in r:
  389. w.write(line.replace("ROW_FORMAT=COMPRESSED", "ROW_FORMAT=DYNAMIC"))
  390. old_sql_file_path.unlink()
  391. def extract_sql_gzip(sql_gz_path):
  392. import subprocess
  393. try:
  394. original_file = sql_gz_path
  395. decompressed_file = original_file.rstrip(".gz")
  396. cmd = 'gzip --decompress --force < {0} > {1}'.format(original_file, decompressed_file)
  397. subprocess.check_call(cmd, shell=True)
  398. except Exception:
  399. raise
  400. return decompressed_file
  401. def extract_files(site_name, file_path):
  402. import shutil
  403. import subprocess
  404. from frappe.utils import get_bench_relative_path
  405. file_path = get_bench_relative_path(file_path)
  406. # Need to do frappe.init to maintain the site locals
  407. frappe.init(site=site_name)
  408. abs_site_path = os.path.abspath(frappe.get_site_path())
  409. # Copy the files to the parent directory and extract
  410. shutil.copy2(os.path.abspath(file_path), abs_site_path)
  411. # Get the file name splitting the file path on
  412. tar_name = os.path.split(file_path)[1]
  413. tar_path = os.path.join(abs_site_path, tar_name)
  414. try:
  415. if file_path.endswith(".tar"):
  416. subprocess.check_output(['tar', 'xvf', tar_path, '--strip', '2'], cwd=abs_site_path)
  417. elif file_path.endswith(".tgz"):
  418. subprocess.check_output(['tar', 'zxvf', tar_path, '--strip', '2'], cwd=abs_site_path)
  419. except:
  420. raise
  421. finally:
  422. frappe.destroy()
  423. return tar_path
  424. def is_downgrade(sql_file_path, verbose=False):
  425. """checks if input db backup will get downgraded on current bench"""
  426. # This function is only tested with mariadb
  427. # TODO: Add postgres support
  428. if frappe.conf.db_type not in (None, "mariadb"):
  429. return False
  430. from semantic_version import Version
  431. head = "INSERT INTO `tabInstalled Application` VALUES"
  432. with open(sql_file_path) as f:
  433. for line in f:
  434. if head in line:
  435. # 'line' (str) format: ('2056588823','2020-05-11 18:21:31.488367','2020-06-12 11:49:31.079506','Administrator','Administrator',0,'Installed Applications','installed_applications','Installed Applications',1,'frappe','v10.1.71-74 (3c50d5e) (v10.x.x)','v10.x.x'),('855c640b8e','2020-05-11 18:21:31.488367','2020-06-12 11:49:31.079506','Administrator','Administrator',0,'Installed Applications','installed_applications','Installed Applications',2,'your_custom_app','0.0.1','master')
  436. line = line.strip().lstrip(head).rstrip(";").strip()
  437. app_rows = frappe.safe_eval(line)
  438. # check if iterable consists of tuples before trying to transform
  439. apps_list = app_rows if all(isinstance(app_row, (tuple, list, set)) for app_row in app_rows) else (app_rows, )
  440. # 'all_apps' (list) format: [('frappe', '12.x.x-develop ()', 'develop'), ('your_custom_app', '0.0.1', 'master')]
  441. all_apps = [ x[-3:] for x in apps_list ]
  442. for app in all_apps:
  443. app_name = app[0]
  444. app_version = app[1].split(" ")[0]
  445. if app_name == "frappe":
  446. try:
  447. current_version = Version(frappe.__version__)
  448. backup_version = Version(app_version[1:] if app_version[0] == "v" else app_version)
  449. except ValueError:
  450. return False
  451. downgrade = backup_version > current_version
  452. if verbose and downgrade:
  453. print(f"Your site will be downgraded from Frappe {backup_version} to {current_version}")
  454. return downgrade
  455. def is_partial(sql_file_path):
  456. with open(sql_file_path) as f:
  457. header = " ".join(f.readline() for _ in range(5))
  458. if "Partial Backup" in header:
  459. return True
  460. return False
  461. def partial_restore(sql_file_path, verbose=False):
  462. sql_file = extract_sql_from_archive(sql_file_path)
  463. if frappe.conf.db_type in (None, "mariadb"):
  464. from frappe.database.mariadb.setup_db import import_db_from_sql
  465. elif frappe.conf.db_type == "postgres":
  466. from frappe.database.postgres.setup_db import import_db_from_sql
  467. import warnings
  468. from click import style
  469. warn = style(
  470. "Delete the tables you want to restore manually before attempting"
  471. " partial restore operation for PostreSQL databases",
  472. fg="yellow"
  473. )
  474. warnings.warn(warn)
  475. import_db_from_sql(source_sql=sql_file, verbose=verbose)
  476. # Removing temporarily created file
  477. if sql_file != sql_file_path:
  478. os.remove(sql_file)
  479. def validate_database_sql(path, _raise=True):
  480. """Check if file has contents and if DefaultValue table exists
  481. Args:
  482. path (str): Path of the decompressed SQL file
  483. _raise (bool, optional): Raise exception if invalid file. Defaults to True.
  484. """
  485. empty_file = False
  486. missing_table = True
  487. error_message = ""
  488. if not os.path.getsize(path):
  489. error_message = f"{path} is an empty file!"
  490. empty_file = True
  491. # dont bother checking if empty file
  492. if not empty_file:
  493. with open(path, "r") as f:
  494. for line in f:
  495. if 'tabDefaultValue' in line:
  496. missing_table = False
  497. break
  498. if missing_table:
  499. error_message = "Table `tabDefaultValue` not found in file."
  500. if error_message:
  501. import click
  502. click.secho(error_message, fg="red")
  503. if _raise and (missing_table or empty_file):
  504. raise frappe.InvalidDatabaseFile