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.
 
 
 
 
 
 

420 lines
12 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. # called from wnf.py
  4. # lib/wnf.py --install [rootpassword] [dbname] [source]
  5. from __future__ import unicode_literals, print_function
  6. import os, json, sys, subprocess, shutil
  7. import frappe
  8. import frappe.database
  9. import getpass
  10. import importlib
  11. from frappe import _
  12. from frappe.model.db_schema import DbManager
  13. from frappe.model.sync import sync_for
  14. from frappe.utils.fixtures import sync_fixtures
  15. from frappe.website import render
  16. from frappe.desk.doctype.desktop_icon.desktop_icon import sync_from_app
  17. from frappe.utils.password import create_auth_table
  18. from frappe.utils.global_search import setup_global_search_table
  19. from frappe.modules.utils import sync_customizations
  20. def install_db(root_login="root", root_password=None, db_name=None, source_sql=None,
  21. admin_password=None, verbose=True, force=0, site_config=None, reinstall=False):
  22. make_conf(db_name, site_config=site_config)
  23. frappe.flags.in_install_db = True
  24. if reinstall:
  25. frappe.connect(db_name=db_name)
  26. dbman = DbManager(frappe.local.db)
  27. dbman.create_database(db_name)
  28. else:
  29. frappe.local.db = get_root_connection(root_login, root_password)
  30. frappe.local.session = frappe._dict({'user':'Administrator'})
  31. create_database_and_user(force, verbose)
  32. frappe.conf.admin_password = frappe.conf.admin_password or admin_password
  33. frappe.connect(db_name=db_name)
  34. check_if_ready_for_barracuda()
  35. import_db_from_sql(source_sql, verbose)
  36. if not 'tabDefaultValue' in frappe.db.get_tables():
  37. print('''Database not installed, this can due to lack of permission, or that the database name exists.
  38. Check your mysql root password, or use --force to reinstall''')
  39. sys.exit(1)
  40. remove_missing_apps()
  41. create_auth_table()
  42. setup_global_search_table()
  43. create_user_settings_table()
  44. frappe.flags.in_install_db = False
  45. def create_database_and_user(force, verbose):
  46. db_name = frappe.local.conf.db_name
  47. dbman = DbManager(frappe.local.db)
  48. if force or (db_name not in dbman.get_database_list()):
  49. dbman.delete_user(db_name)
  50. dbman.drop_database(db_name)
  51. else:
  52. raise Exception("Database %s already exists" % (db_name,))
  53. dbman.create_user(db_name, frappe.conf.db_password)
  54. if verbose: print("Created user %s" % db_name)
  55. dbman.create_database(db_name)
  56. if verbose: print("Created database %s" % db_name)
  57. dbman.grant_all_privileges(db_name, db_name)
  58. dbman.flush_privileges()
  59. if verbose: print("Granted privileges to user %s and database %s" % (db_name, db_name))
  60. # close root connection
  61. frappe.db.close()
  62. def create_user_settings_table():
  63. frappe.db.sql_ddl("""create table if not exists __UserSettings (
  64. `user` VARCHAR(180) NOT NULL,
  65. `doctype` VARCHAR(180) NOT NULL,
  66. `data` TEXT,
  67. UNIQUE(user, doctype)
  68. ) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
  69. def import_db_from_sql(source_sql, verbose):
  70. if verbose: print("Starting database import...")
  71. db_name = frappe.conf.db_name
  72. if not source_sql:
  73. source_sql = os.path.join(os.path.dirname(frappe.__file__), 'data', 'Framework.sql')
  74. DbManager(frappe.local.db).restore_database(db_name, source_sql, db_name, frappe.conf.db_password)
  75. if verbose: print("Imported from database %s" % source_sql)
  76. def get_root_connection(root_login='root', root_password=None):
  77. if not frappe.local.flags.root_connection:
  78. if root_login:
  79. if not root_password:
  80. root_password = frappe.conf.get("root_password") or None
  81. if not root_password:
  82. root_password = getpass.getpass("MySQL root password: ")
  83. frappe.local.flags.root_connection = frappe.database.Database(user=root_login, password=root_password)
  84. return frappe.local.flags.root_connection
  85. def install_app(name, verbose=False, set_as_patched=True):
  86. frappe.flags.in_install = name
  87. frappe.clear_cache()
  88. app_hooks = frappe.get_hooks(app_name=name)
  89. installed_apps = frappe.get_installed_apps()
  90. # install pre-requisites
  91. if app_hooks.required_apps:
  92. for app in app_hooks.required_apps:
  93. install_app(app)
  94. frappe.flags.in_install = name
  95. frappe.clear_cache()
  96. if name not in frappe.get_all_apps():
  97. raise Exception("App not in apps.txt")
  98. if name in installed_apps:
  99. frappe.msgprint(_("App {0} already installed").format(name))
  100. return
  101. print("Installing {0}...".format(name))
  102. if name != "frappe":
  103. frappe.only_for("System Manager")
  104. for before_install in app_hooks.before_install or []:
  105. out = frappe.get_attr(before_install)()
  106. if out==False:
  107. return
  108. if name != "frappe":
  109. add_module_defs(name)
  110. sync_for(name, force=True, sync_everything=True, verbose=verbose, reset_permissions=True)
  111. sync_from_app(name)
  112. add_to_installed_apps(name)
  113. frappe.get_doc('Portal Settings', 'Portal Settings').sync_menu()
  114. if set_as_patched:
  115. set_all_patches_as_completed(name)
  116. for after_install in app_hooks.after_install or []:
  117. frappe.get_attr(after_install)()
  118. sync_fixtures(name)
  119. sync_customizations(name)
  120. frappe.flags.in_install = False
  121. def add_to_installed_apps(app_name, rebuild_website=True):
  122. installed_apps = frappe.get_installed_apps()
  123. if not app_name in installed_apps:
  124. installed_apps.append(app_name)
  125. frappe.db.set_global("installed_apps", json.dumps(installed_apps))
  126. frappe.db.commit()
  127. post_install(rebuild_website)
  128. def remove_from_installed_apps(app_name):
  129. installed_apps = frappe.get_installed_apps()
  130. if app_name in installed_apps:
  131. installed_apps.remove(app_name)
  132. frappe.db.set_global("installed_apps", json.dumps(installed_apps))
  133. frappe.db.commit()
  134. if frappe.flags.in_install:
  135. post_install()
  136. def remove_app(app_name, dry_run=False, yes=False):
  137. """Delete app and all linked to the app's module with the app."""
  138. if not dry_run and not yes:
  139. confirm = raw_input("All doctypes (including custom), modules related to this app will be deleted. Are you sure you want to continue (y/n) ? ")
  140. if confirm!="y":
  141. return
  142. from frappe.utils.backups import scheduled_backup
  143. print("Backing up...")
  144. scheduled_backup(ignore_files=True)
  145. drop_doctypes = []
  146. # remove modules, doctypes, roles
  147. for module_name in frappe.get_module_list(app_name):
  148. for doctype in frappe.get_list("DocType", filters={"module": module_name},
  149. fields=["name", "issingle"]):
  150. print("removing DocType {0}...".format(doctype.name))
  151. if not dry_run:
  152. frappe.delete_doc("DocType", doctype.name)
  153. if not doctype.issingle:
  154. drop_doctypes.append(doctype.name)
  155. # remove reports, pages and web forms
  156. for doctype in ("Report", "Page", "Web Form"):
  157. for record in frappe.get_list(doctype, filters={"module": module_name}):
  158. print("removing {0} {1}...".format(doctype, record.name))
  159. if not dry_run:
  160. frappe.delete_doc(doctype, record.name)
  161. print("removing Module {0}...".format(module_name))
  162. if not dry_run:
  163. frappe.delete_doc("Module Def", module_name)
  164. # delete desktop icons
  165. frappe.db.sql('delete from `tabDesktop Icon` where app=%s', app_name)
  166. remove_from_installed_apps(app_name)
  167. if not dry_run:
  168. # drop tables after a commit
  169. frappe.db.commit()
  170. for doctype in set(drop_doctypes):
  171. frappe.db.sql("drop table `tab{0}`".format(doctype))
  172. def post_install(rebuild_website=False):
  173. if rebuild_website:
  174. render.clear_cache()
  175. init_singles()
  176. frappe.db.commit()
  177. frappe.clear_cache()
  178. def set_all_patches_as_completed(app):
  179. patch_path = os.path.join(frappe.get_pymodule_path(app), "patches.txt")
  180. if os.path.exists(patch_path):
  181. for patch in frappe.get_file_items(patch_path):
  182. frappe.get_doc({
  183. "doctype": "Patch Log",
  184. "patch": patch
  185. }).insert(ignore_permissions=True)
  186. frappe.db.commit()
  187. def init_singles():
  188. singles = [single['name'] for single in frappe.get_all("DocType", filters={'issingle': True})]
  189. for single in singles:
  190. if not frappe.db.get_singles_dict(single):
  191. doc = frappe.new_doc(single)
  192. doc.flags.ignore_mandatory=True
  193. doc.flags.ignore_validate=True
  194. doc.save()
  195. def make_conf(db_name=None, db_password=None, site_config=None):
  196. site = frappe.local.site
  197. make_site_config(db_name, db_password, site_config)
  198. sites_path = frappe.local.sites_path
  199. frappe.destroy()
  200. frappe.init(site, sites_path=sites_path)
  201. def make_site_config(db_name=None, db_password=None, site_config=None):
  202. frappe.create_folder(os.path.join(frappe.local.site_path))
  203. site_file = get_site_config_path()
  204. if not os.path.exists(site_file):
  205. if not (site_config and isinstance(site_config, dict)):
  206. site_config = get_conf_params(db_name, db_password)
  207. with open(site_file, "w") as f:
  208. f.write(json.dumps(site_config, indent=1, sort_keys=True))
  209. def update_site_config(key, value, validate=True, site_config_path=None):
  210. """Update a value in site_config"""
  211. if not site_config_path:
  212. site_config_path = get_site_config_path()
  213. with open(site_config_path, "r") as f:
  214. site_config = json.loads(f.read())
  215. # In case of non-int value
  216. if value in ('0', '1'):
  217. value = int(value)
  218. # boolean
  219. if value == 'false': value = False
  220. if value == 'true': value = True
  221. # remove key if value is None
  222. if value == "None":
  223. if key in site_config:
  224. del site_config[key]
  225. else:
  226. site_config[key] = value
  227. with open(site_config_path, "w") as f:
  228. f.write(json.dumps(site_config, indent=1, sort_keys=True))
  229. if frappe.local.conf:
  230. frappe.local.conf[key] = value
  231. def get_site_config_path():
  232. return os.path.join(frappe.local.site_path, "site_config.json")
  233. def get_conf_params(db_name=None, db_password=None):
  234. if not db_name:
  235. db_name = raw_input("Database Name: ")
  236. if not db_name:
  237. raise Exception("Database Name Required")
  238. if not db_password:
  239. from frappe.utils import random_string
  240. db_password = random_string(16)
  241. return {"db_name": db_name, "db_password": db_password}
  242. def make_site_dirs():
  243. site_public_path = os.path.join(frappe.local.site_path, 'public')
  244. site_private_path = os.path.join(frappe.local.site_path, 'private')
  245. for dir_path in (
  246. os.path.join(site_private_path, 'backups'),
  247. os.path.join(site_public_path, 'files'),
  248. os.path.join(site_private_path, 'files'),
  249. os.path.join(frappe.local.site_path, 'task-logs')):
  250. if not os.path.exists(dir_path):
  251. os.makedirs(dir_path)
  252. locks_dir = frappe.get_site_path('locks')
  253. if not os.path.exists(locks_dir):
  254. os.makedirs(locks_dir)
  255. def add_module_defs(app):
  256. modules = frappe.get_module_list(app)
  257. for module in modules:
  258. d = frappe.new_doc("Module Def")
  259. d.app_name = app
  260. d.module_name = module
  261. d.save(ignore_permissions=True)
  262. def remove_missing_apps():
  263. apps = ('frappe_subscription', 'shopping_cart')
  264. installed_apps = json.loads(frappe.db.get_global("installed_apps") or "[]")
  265. for app in apps:
  266. if app in installed_apps:
  267. try:
  268. importlib.import_module(app)
  269. except ImportError:
  270. installed_apps.remove(app)
  271. frappe.db.set_global("installed_apps", json.dumps(installed_apps))
  272. def check_if_ready_for_barracuda():
  273. mariadb_variables = frappe._dict(frappe.db.sql("""show variables"""))
  274. for key, value in {
  275. "innodb_file_format": "Barracuda",
  276. "innodb_file_per_table": "ON",
  277. "innodb_large_prefix": "ON",
  278. "character_set_server": "utf8mb4",
  279. "collation_server": "utf8mb4_unicode_ci"
  280. }.items():
  281. if mariadb_variables.get(key) != value:
  282. site = frappe.local.site
  283. msg = ("Creation of your site - {x} failed because MariaDB is not properly {sep}"
  284. "configured to use the Barracuda storage engine. {sep}"
  285. "Please add the settings below to MariaDB's my.cnf, restart MariaDB then {sep}"
  286. "run `bench new-site {x}` again.{sep2}"
  287. "").format(x=site, sep2="\n"*2, sep="\n")
  288. print_db_config(msg, expected_config_for_barracuda)
  289. raise frappe.exceptions.ImproperDBConfigurationError(
  290. reason="MariaDB default file format is not Barracuda"
  291. )
  292. def print_db_config(explanation, config_text):
  293. print("="*80)
  294. print(explanation)
  295. print(config_text)
  296. print("="*80)
  297. def extract_sql_gzip(sql_gz_path):
  298. try:
  299. subprocess.check_call(['gzip', '-d', '-v', '-f', sql_gz_path])
  300. except:
  301. raise
  302. return sql_gz_path[:-3]
  303. def extract_tar_files(site_name, file_path, folder_name):
  304. # Need to do frappe.init to maintain the site locals
  305. frappe.init(site=site_name)
  306. abs_site_path = os.path.abspath(frappe.get_site_path())
  307. # Copy the files to the parent directory and extract
  308. shutil.copy2(os.path.abspath(file_path), abs_site_path)
  309. # Get the file name splitting the file path on
  310. tar_name = os.path.split(file_path)[1]
  311. tar_path = os.path.join(abs_site_path, tar_name)
  312. try:
  313. subprocess.check_output(['tar', 'xvf', tar_path, '--strip', '2'], cwd=abs_site_path)
  314. except:
  315. raise
  316. finally:
  317. frappe.destroy()
  318. return tar_path
  319. expected_config_for_barracuda = """[mysqld]
  320. innodb-file-format=barracuda
  321. innodb-file-per-table=1
  322. innodb-large-prefix=1
  323. character-set-client-handshake = FALSE
  324. character-set-server = utf8mb4
  325. collation-server = utf8mb4_unicode_ci
  326. [mysql]
  327. default-character-set = utf8mb4
  328. """