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.
 
 
 
 
 
 

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