Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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