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.
 
 
 
 
 
 

268 lines
8.0 KiB

  1. # Copyright (c) 2013, Web Notes 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, sys, json
  7. import webnotes
  8. import webnotes.db
  9. import getpass
  10. from webnotes.model.db_schema import DbManager
  11. from webnotes.model.sync import sync_for
  12. from webnotes.utils import cstr
  13. class Installer:
  14. def __init__(self, root_login, root_password=None, db_name=None, site=None, site_config=None):
  15. make_conf(db_name, site=site, site_config=site_config)
  16. self.site = site
  17. self.make_connection(root_login, root_password)
  18. webnotes.local.conn = self.conn
  19. webnotes.local.session = webnotes._dict({'user':'Administrator'})
  20. self.dbman = DbManager(self.conn)
  21. def make_connection(self, root_login, root_password):
  22. if root_login:
  23. if not root_password:
  24. root_password = webnotes.conf.get("root_password") or None
  25. if not root_password:
  26. root_password = getpass.getpass("MySQL root password: ")
  27. self.root_password = root_password
  28. self.conn = webnotes.db.Database(user=root_login, password=root_password)
  29. def install(self, db_name, source_sql=None, admin_password = 'admin', verbose=0,
  30. force=0):
  31. if force or (db_name not in self.dbman.get_database_list()):
  32. # delete user (if exists)
  33. self.dbman.delete_user(db_name)
  34. else:
  35. raise Exception("Database %s already exists" % (db_name,))
  36. # create user and db
  37. self.dbman.create_user(db_name, webnotes.conf.db_password)
  38. if verbose: print "Created user %s" % db_name
  39. # create a database
  40. self.dbman.create_database(db_name)
  41. if verbose: print "Created database %s" % db_name
  42. # grant privileges to user
  43. self.dbman.grant_all_privileges(db_name, db_name)
  44. if verbose: print "Granted privileges to user %s and database %s" % (db_name, db_name)
  45. # flush user privileges
  46. self.dbman.flush_privileges()
  47. # close root connection
  48. self.conn.close()
  49. webnotes.connect(db_name=db_name, site=self.site)
  50. self.dbman = DbManager(webnotes.conn)
  51. # import in db_name
  52. if verbose: print "Starting database import..."
  53. # get the path of the sql file to import
  54. if not source_sql:
  55. source_sql = os.path.join(os.path.dirname(webnotes.__file__), "..",
  56. 'conf', 'Framework.sql')
  57. self.dbman.restore_database(db_name, source_sql, db_name, webnotes.conf.db_password)
  58. if verbose: print "Imported from database %s" % source_sql
  59. self.create_auth_table()
  60. # fresh app
  61. if 'Framework.sql' in source_sql:
  62. if verbose: print "Installing app..."
  63. self.install_app(verbose=verbose)
  64. # update admin password
  65. self.update_admin_password(admin_password)
  66. # create public folder
  67. from webnotes.install_lib import setup_public_folder
  68. setup_public_folder.make(site=self.site)
  69. if not self.site:
  70. from webnotes.build import bundle
  71. bundle(False)
  72. return db_name
  73. def install_app(self, verbose=False):
  74. sync_for("lib", force=True, sync_everything=True, verbose=verbose)
  75. self.import_core_docs()
  76. try:
  77. from startup import install
  78. except ImportError, e:
  79. install = None
  80. if os.path.exists("app"):
  81. sync_for("app", force=True, sync_everything=True, verbose=verbose)
  82. if os.path.exists(os.path.join("app", "startup", "install_fixtures")):
  83. install_fixtures()
  84. # build website sitemap
  85. from website.doctype.website_sitemap_config.website_sitemap_config import build_website_sitemap_config
  86. build_website_sitemap_config()
  87. if verbose: print "Completing App Import..."
  88. install and install.post_import()
  89. if verbose: print "Updating patches..."
  90. self.set_all_patches_as_completed()
  91. self.assign_all_role_to_administrator()
  92. def update_admin_password(self, password):
  93. from webnotes.auth import _update_password
  94. webnotes.conn.begin()
  95. _update_password("Administrator", webnotes.conf.get("admin_password") or password)
  96. webnotes.conn.commit()
  97. def import_core_docs(self):
  98. install_docs = [
  99. # profiles
  100. {'doctype':'Profile', 'name':'Administrator', 'first_name':'Administrator',
  101. 'email':'admin@localhost', 'enabled':1},
  102. {'doctype':'Profile', 'name':'Guest', 'first_name':'Guest',
  103. 'email':'guest@localhost', 'enabled':1},
  104. # userroles
  105. {'doctype':'UserRole', 'parent': 'Administrator', 'role': 'Administrator',
  106. 'parenttype':'Profile', 'parentfield':'user_roles'},
  107. {'doctype':'UserRole', 'parent': 'Guest', 'role': 'Guest',
  108. 'parenttype':'Profile', 'parentfield':'user_roles'},
  109. {'doctype': "Role", "role_name": "Report Manager"}
  110. ]
  111. webnotes.conn.begin()
  112. for d in install_docs:
  113. bean = webnotes.bean(d)
  114. bean.insert()
  115. webnotes.conn.commit()
  116. def set_all_patches_as_completed(self):
  117. try:
  118. from patches.patch_list import patch_list
  119. except ImportError, e:
  120. print "No patches to update."
  121. return
  122. for patch in patch_list:
  123. webnotes.doc({
  124. "doctype": "Patch Log",
  125. "patch": patch
  126. }).insert()
  127. webnotes.conn.commit()
  128. def assign_all_role_to_administrator(self):
  129. webnotes.bean("Profile", "Administrator").get_controller().add_roles(*webnotes.conn.sql_list("""
  130. select name from tabRole"""))
  131. webnotes.conn.commit()
  132. def create_auth_table(self):
  133. webnotes.conn.sql_ddl("""create table if not exists __Auth (
  134. `user` VARCHAR(180) NOT NULL PRIMARY KEY,
  135. `password` VARCHAR(180) NOT NULL
  136. ) ENGINE=InnoDB DEFAULT CHARSET=utf8""")
  137. def make_conf(db_name=None, db_password=None, site=None, site_config=None):
  138. try:
  139. from werkzeug.exceptions import NotFound
  140. import conf
  141. try:
  142. webnotes.init(site=site)
  143. except NotFound:
  144. pass
  145. if not site and webnotes.conf.site:
  146. site = webnotes.conf.site
  147. if site:
  148. # conf exists and site is specified, create site_config.json
  149. make_site_config(site, db_name, db_password, site_config)
  150. elif os.path.exists("conf.py"):
  151. print "conf.py exists"
  152. else:
  153. # pyc file exists but py doesn't
  154. raise ImportError
  155. except ImportError:
  156. if site:
  157. raise Exception("conf.py does not exist")
  158. else:
  159. # create conf.py
  160. with open(os.path.join("lib", "conf", "conf.py"), "r") as confsrc:
  161. with open("conf.py", "w") as conftar:
  162. conftar.write(confsrc.read() % get_conf_params(db_name, db_password))
  163. webnotes.destroy()
  164. webnotes.init(site=site)
  165. def make_site_config(site, db_name=None, db_password=None, site_config=None):
  166. import conf
  167. if not getattr(conf, "sites_dir", None):
  168. raise Exception("sites_dir missing in conf.py")
  169. site_path = os.path.join(conf.sites_dir, site)
  170. if not os.path.exists(site_path):
  171. os.mkdir(site_path)
  172. site_file = os.path.join(site_path, "site_config.json")
  173. if not os.path.exists(site_file):
  174. if not (site_config and isinstance(site_config, dict)):
  175. site_config = get_conf_params(db_name, db_password)
  176. with open(site_file, "w") as f:
  177. f.write(json.dumps(site_config, indent=1, sort_keys=True))
  178. def get_conf_params(db_name=None, db_password=None):
  179. if not db_name:
  180. db_name = raw_input("Database Name: ")
  181. if not db_name:
  182. raise Exception("Database Name Required")
  183. if not db_password:
  184. from webnotes.utils import random_string
  185. db_password = random_string(16)
  186. return {"db_name": db_name, "db_password": db_password}
  187. def install_fixtures():
  188. print "Importing install fixtures..."
  189. for basepath, folders, files in os.walk(os.path.join("app", "startup", "install_fixtures")):
  190. for f in files:
  191. f = cstr(f)
  192. if f.endswith(".json"):
  193. print "Importing " + f
  194. with open(os.path.join(basepath, f), "r") as infile:
  195. webnotes.bean(json.loads(infile.read())).insert_or_update()
  196. webnotes.conn.commit()
  197. if f.endswith(".csv"):
  198. from core.page.data_import_tool.data_import_tool import import_file_by_path
  199. import_file_by_path(os.path.join(basepath, f), ignore_links = True, overwrite=True)
  200. webnotes.conn.commit()
  201. if os.path.exists(os.path.join("app", "startup", "install_fixtures", "files")):
  202. if not os.path.exists(os.path.join("public", "files")):
  203. os.makedirs(os.path.join("public", "files"))
  204. os.system("cp -r %s %s" % (os.path.join("app", "startup", "install_fixtures", "files", "*"),
  205. os.path.join("public", "files")))