示例#1
0
def set_config(context, key, value):
	"Insert/Update a value in site_config.json"
	from frappe.installer import update_site_config
	for site in context.sites:
		frappe.init(site=site)
		update_site_config(key, value)
		frappe.destroy()
示例#2
0
def scheduler(context, state, site=None):
    import frappe.utils.scheduler
    from frappe.installer import update_site_config

    if not site:
        site = get_site(context)

    try:
        frappe.init(site=site)

        if state == "pause":
            update_site_config("pause_scheduler", 1)
        elif state == "resume":
            update_site_config("pause_scheduler", 0)
        elif state == "disable":
            frappe.connect()
            frappe.utils.scheduler.disable_scheduler()
            frappe.db.commit()
        elif state == "enable":
            frappe.connect()
            frappe.utils.scheduler.enable_scheduler()
            frappe.db.commit()

        print("Scheduler {0}d for site {1}".format(state, site))

    finally:
        frappe.destroy()
示例#3
0
def set_key_in_site_config(key, site, site_config_path):
    site_config = get_site_config_from_path(site_config_path)
    value = site_config.get(key)
    if value:
        print('Set {key} in site config for site: {site}'.format(key=key, site=site))
        update_site_config(key, value,
                            site_config_path=os.path.join(os.getcwd(), site, "site_config.json"))
示例#4
0
def scheduler(context, state, site=None):
    from frappe.installer import update_site_config
    import frappe.utils.scheduler

    if not site:
        site = get_site(context)

    try:
        frappe.init(site=site)

        if state == "pause":
            update_site_config("pause_scheduler", 1)
        elif state == "resume":
            update_site_config("pause_scheduler", 0)
        elif state == "disable":
            frappe.connect()
            frappe.utils.scheduler.disable_scheduler()
            frappe.db.commit()
        elif state == "enable":
            frappe.connect()
            frappe.utils.scheduler.enable_scheduler()
            frappe.db.commit()

        print "Scheduler {0}d for site {1}".format(state, site)

    finally:
        frappe.destroy()
示例#5
0
def set_config(context, key, value, global_=False, parse=False, as_dict=False):
    "Insert/Update a value in site_config.json"
    from frappe.installer import update_site_config

    if as_dict:
        from frappe.utils.commands import warn
        warn("--as-dict will be deprecated in v14. Use --parse instead",
             category=PendingDeprecationWarning)
        parse = as_dict

    if parse:
        import ast
        value = ast.literal_eval(value)

    if global_:
        sites_path = os.getcwd()
        common_site_config_path = os.path.join(sites_path,
                                               'common_site_config.json')
        update_site_config(key,
                           value,
                           validate=False,
                           site_config_path=common_site_config_path)
    else:
        for site in context.sites:
            frappe.init(site=site)
            update_site_config(key, value, validate=False)
            frappe.destroy()
示例#6
0
def setup_global_help(db_type=None, root_password=None):
	'''setup help table in a separate database that will be
	shared by the whole bench and set `global_help_setup` as 1 in
	common_site_config.json'''

	from frappe.installer import update_site_config

	frappe.local.flags = frappe._dict()
	frappe.local.flags.in_setup_help = True
	frappe.local.flags.in_install = True
	frappe.local.lang = 'en'
	frappe.local.conf = frappe.get_site_config(sites_path='.')

	update_site_config('global_help_setup', 1,
		site_config_path=os.path.join('.', 'common_site_config.json'))

	if root_password:
		frappe.local.conf.root_password = root_password

	if not frappe.local.conf.db_type:
		frappe.local.conf.db_type = db_type


	from frappe.utils.help import sync
	sync()
def update_limits(limits_dict):
	'''Add/Update limit in site_config'''
	limits = get_limits()
	limits.update(limits_dict)
	update_site_config("limits", limits, validate=False)
	disable_users(limits)
	frappe.local.conf.limits = limits
示例#8
0
def scheduler(context, state, site=None):
	from frappe.installer import update_site_config
	import frappe.utils.scheduler

	if not site:
		site = get_site(context)

	try:
		frappe.init(site=site)

		if state == 'pause':
			update_site_config('pause_scheduler', 1)
		elif state == 'resume':
			update_site_config('pause_scheduler', 0)
		elif state == 'disable':
			frappe.connect()
			frappe.utils.scheduler.disable_scheduler()
			frappe.db.commit()
		elif state == 'enable':
			frappe.connect()
			frappe.utils.scheduler.enable_scheduler()
			frappe.db.commit()

		print('Scheduler {0}d for site {1}'.format(state, site))

	finally:
		frappe.destroy()
示例#9
0
def set_config(context, key, value):
    "Insert/Update a value in site_config.json"
    from frappe.installer import update_site_config
    for site in context.sites:
        frappe.init(site=site)
        update_site_config(key, value)
        frappe.destroy()
示例#10
0
def get_encryption_key():
	from frappe.installer import update_site_config

	if 'encryption_key' not in frappe.local.conf:
		encryption_key = Fernet.generate_key().decode()
		update_site_config('encryption_key', encryption_key)
		frappe.local.conf.encryption_key = encryption_key

	return frappe.local.conf.encryption_key
示例#11
0
def get_encryption_key():
    from frappe.installer import update_site_config

    if "encryption_key" not in frappe.local.conf:
        encryption_key = Fernet.generate_key().decode()
        update_site_config("encryption_key", encryption_key)
        frappe.local.conf.encryption_key = encryption_key

    return frappe.local.conf.encryption_key
示例#12
0
def restore_postgres(config, site_config, database_file):
    # common config
    common_site_config_path = os.path.join(os.getcwd(),
                                           COMMON_SITE_CONFIG_FILE)

    db_root_user = config.get('root_login')
    if not db_root_user:
        postgres_user = os.environ.get('DB_ROOT_USER')
        if not postgres_user:
            print('Variable DB_ROOT_USER not set')
            exit(1)

        db_root_user = postgres_user
        update_site_config("root_login",
                           db_root_user,
                           validate=False,
                           site_config_path=common_site_config_path)

    db_root_password = config.get('root_password')
    if not db_root_password:
        root_password = get_password('POSTGRES_PASSWORD')
        if not root_password:
            print('Variable POSTGRES_PASSWORD not set')
            exit(1)

        db_root_password = root_password
        update_site_config("root_password",
                           db_root_password,
                           validate=False,
                           site_config_path=common_site_config_path)

    # site config
    db_host = site_config.get('db_host')
    db_port = site_config.get('db_port', 5432)
    db_name = site_config.get('db_name')
    db_password = site_config.get('db_password')

    psql_command = ["psql"]
    psql_uri = f"postgres://{db_root_user}:{db_root_password}@{db_host}:{db_port}"

    print('Restoring PostgreSQL')
    run_command(psql_command +
                [psql_uri, "-c", f"DROP DATABASE IF EXISTS \"{db_name}\""])
    run_command(psql_command +
                [psql_uri, "-c", f"DROP USER IF EXISTS {db_name}"])
    run_command(psql_command +
                [psql_uri, "-c", f"CREATE DATABASE \"{db_name}\""])
    run_command(
        psql_command +
        [psql_uri, "-c", f"CREATE user {db_name} password '{db_password}'"])
    run_command(psql_command + [
        psql_uri, "-c",
        f"GRANT ALL PRIVILEGES ON DATABASE \"{db_name}\" TO {db_name}"
    ])
    with open(database_file.replace('.gz', ''), 'r') as db_file:
        run_command(psql_command + [f"{psql_uri}/{db_name}", "<"],
                    stdin=db_file)
示例#13
0
def set_config(context, key, value, as_dict=False):
	"Insert/Update a value in site_config.json"
	from frappe.installer import update_site_config
	import ast
	if as_dict:
		value = ast.literal_eval(value)
	for site in context.sites:
		frappe.init(site=site)
		update_site_config(key, value, validate=False)
		frappe.destroy()
示例#14
0
def set_config(context, key, value, as_dict=False):
	"Insert/Update a value in site_config.json"
	from frappe.installer import update_site_config
	import ast
	if as_dict:
		value = ast.literal_eval(value)
	for site in context.sites:
		frappe.init(site=site)
		update_site_config(key, value, validate=False)
		frappe.destroy()
示例#15
0
def clear_limit(key):
	'''Remove a limit option from site_config'''
	limits = get_limits()
	to_clear = [key] if isinstance(key, basestring) else key
	for key in to_clear:
		if key in limits:
			del limits[key]

	update_site_config("limits", limits, validate=False)
	frappe.conf.limits = limits
示例#16
0
def clear_limit(key):
    """Remove a limit option from site_config"""
    limits = get_limits()
    to_clear = [key] if isinstance(key, basestring) else key
    for key in to_clear:
        if key in limits:
            del limits[key]

    update_site_config("limits", limits, validate=False)
    frappe.conf.limits = limits
示例#17
0
def set_maintenance_mode(context, state, site=None):
	from frappe.installer import update_site_config
	if not site:
		site = get_site(context)

	try:
		frappe.init(site=site)
		update_site_config('maintenance_mode', 1 if (state == 'on') else 0)

	finally:
		frappe.destroy()
示例#18
0
def add_non_standard_user_types():
    user_types = get_user_types_data()

    user_type_limit = {}
    for user_type, data in iteritems(user_types):
        user_type_limit.setdefault(frappe.scrub(user_type), 10)

    update_site_config("user_type_doctype_limit", user_type_limit)

    for user_type, data in iteritems(user_types):
        create_custom_role(data)
        create_user_type(user_type, data)
示例#19
0
def make_support_user(user, password):
	if frappe.conf.erpnext_support_user and frappe.conf.erpnext_support_password:
		return json.dumps({
			"user": frappe.conf.erpnext_support_user,
			"password": frappe.conf.erpnext_support_password
		})

	role = frappe.db.exists('Role', 'Support Bot')

	if not role:
		role = frappe.get_doc({
			"doctype": "Role",
			"role_name": "Support Bot",
		}).insert(ignore_permissions=True)
		role = role.name

	support_user = frappe.get_doc({
		"doctype":"User",
		"email": user,
		"first_name": "Support Bot",
		"send_welcome_email": 0,
		"new_password": password
	}).insert(ignore_permissions=True)

	support_user.add_roles(role)

	role = frappe.db.exists('Role', 'Support Team')
	if role:
		support_user.add_roles(role)

	role = frappe.db.exists('Role', 'System Manager')
	if role:
		support_user.add_roles(role)

	common_site_config_path = os.path.join(frappe.utils.get_bench_path(), 'sites', 'common_site_config.json')
	update_site_config('erpnext_support_user', user, site_config_path=common_site_config_path)
	update_site_config('erpnext_support_password', password, site_config_path=common_site_config_path)

	make_custom_field("Issue", "Bench Site", "bench_site", "Data", "Customer", 1, 0)
	make_custom_field("Issue", "Associated Issue", "associated_issue", "Data", "Customer", 1, 0)
	make_custom_field("Issue", "Raised via Support App", "raised_via_support_app", "Check", "Customer", 1, 0)
	make_custom_field("Issue", "Support Rating", "support_rating", "Int", "Customer", 1, 0)
	make_custom_field("Issue", "Comment", "add_a_comment", "Text", "Customer", 1, 0)
	make_custom_field("Customer", "Self Hosted Details", "self_hosted_details", "Section Break", "Customer POS id", 0, 1)
	make_custom_field("Customer", "Bench Site", "bench_site", "Data", "Self Hosted Details", 0, 0)
	make_custom_field("Customer", "Self Hosted Users", "self_hosted_users", "Int", "Bench Site", 0, 0)
	make_custom_field("Customer", "Self Hosted Expiry", "self_hosted_expiry", "Date", "Self Hosted Users", 0, 0)

	return json.dumps({
		"user": user,
		"password": password
	})
def reset_enabled_scheduler_events(login_manager):
	if login_manager.info.user_type == "System User":
		try:
			frappe.db.set_global('enabled_scheduler_events', None)
		except MySQLdb.OperationalError, e:
			if e.args[0]==1205:
				frappe.log_error(frappe.get_traceback(), "Error in reset_enabled_scheduler_events")
			else:
				raise
		else:
			is_dormant = frappe.conf.get('dormant')
			if is_dormant:
				update_site_config('dormant', 'None')
示例#21
0
def reset_enabled_scheduler_events(login_manager):
	if login_manager.info.user_type == "System User":
		try:
			frappe.db.set_global('enabled_scheduler_events', None)
		except pymysql.InternalError as e:
			if e.args[0]==ER.LOCK_WAIT_TIMEOUT:
				frappe.log_error(frappe.get_traceback(), "Error in reset_enabled_scheduler_events")
			else:
				raise
		else:
			is_dormant = frappe.conf.get('dormant')
			if is_dormant:
				update_site_config('dormant', 'None')
示例#22
0
def reset_enabled_scheduler_events(login_manager):
	if login_manager.info.user_type == "System User":
		try:
			frappe.db.set_global('enabled_scheduler_events', None)
		except MySQLdb.OperationalError, e:
			if e.args[0]==1205:
				frappe.log_error(frappe.get_traceback(), "Error in reset_enabled_scheduler_events")
			else:
				raise
		else:
			is_dormant = frappe.conf.get('dormant')
			if is_dormant:
				update_site_config('dormant', 'None')
示例#23
0
def reset_enabled_scheduler_events(login_manager):
	if login_manager.info.user_type == "System User":
		try:
			if frappe.db.get_global('enabled_scheduler_events'):
				# clear restricted events, someone logged in!
				frappe.db.set_global('enabled_scheduler_events', None)
		except frappe.db.InternalError as e:
			if frappe.db.is_timedout(e):
				frappe.log_error(frappe.get_traceback(), "Error in reset_enabled_scheduler_events")
			else:
				raise
		else:
			is_dormant = frappe.conf.get('dormant')
			if is_dormant:
				update_site_config('dormant', 'None')
示例#24
0
def clear_limits(context, site, limits):
	"""Clears given limit from the site config, and removes limit from site config if its empty"""
	from frappe.limits import clear_limit as _clear_limit
	if not limits:
		return

	if not site:
		site = get_site(context)

	with frappe.init_site(site):
		_clear_limit(limits)

		# Remove limits from the site_config, if it's empty
		limits = get_limits()
		if not limits:
			update_site_config('limits', 'None', validate=False)
示例#25
0
文件: utils.py 项目: yered1/frappe
def set_config(context, key, value, global_ = False, as_dict=False):
	"Insert/Update a value in site_config.json"
	from frappe.installer import update_site_config
	import ast
	if as_dict:
		value = ast.literal_eval(value)

	if global_:
		sites_path = os.getcwd() # big assumption.
		common_site_config_path = os.path.join(sites_path, 'common_site_config.json')
		update_site_config(key, value, validate = False, site_config_path = common_site_config_path)
	else:
		for site in context.sites:
			frappe.init(site=site)
			update_site_config(key, value, validate=False)
			frappe.destroy()
示例#26
0
文件: utils.py 项目: ESS-LLP/frappe
def set_config(context, key, value, global_ = False, as_dict=False):
	"Insert/Update a value in site_config.json"
	from frappe.installer import update_site_config
	import ast
	if as_dict:
		value = ast.literal_eval(value)

	if global_:
		sites_path = os.getcwd() # big assumption.
		common_site_config_path = os.path.join(sites_path, 'common_site_config.json')
		update_site_config(key, value, validate = False, site_config_path = common_site_config_path)
	else:
		for site in context.sites:
			frappe.init(site=site)
			update_site_config(key, value, validate=False)
			frappe.destroy()
示例#27
0
def clear_limits(context, site, limits):
    """Clears given limit from the site config, and removes limit from site config if its empty"""
    from frappe.limits import clear_limit as _clear_limit
    if not limits:
        return

    if not site:
        site = get_site(context)

    with frappe.init_site(site):
        _clear_limit(limits)

        # Remove limits from the site_config, if it's empty
        limits = get_limits()
        if not limits:
            update_site_config('limits', 'None', validate=False)
示例#28
0
def make_support_user(user, password):
    if frappe.conf.erpnext_support_user and frappe.conf.erpnext_support_password:
        return json.dumps({
            "user": frappe.conf.erpnext_support_user,
            "password": frappe.conf.erpnext_support_password
        })

    role = frappe.db.exists("Role", "Support Bot")

    if not role:
        role = frappe.get_doc({
            "doctype": "Role",
            "role_name": "Support Bot",
        }).insert(ignore_permissions=True)
        role = role.name

    support_user = frappe.get_doc({
        "doctype": "User",
        "email": user,
        "first_name": "Support Bot",
        "send_welcome_email": 0,
        "new_password": password
    }).insert(ignore_permissions=True)

    support_user.add_roles(role)

    role = frappe.db.exists("Role", "Support Team")
    if role:
        support_user.add_roles(role)

    role = frappe.db.exists("Role", "System Manager")
    if role:
        support_user.add_roles(role)

    common_site_config_path = os.path.join(frappe.utils.get_bench_path(),
                                           "sites", "common_site_config.json")
    update_site_config("erpnext_support_user",
                       user,
                       site_config_path=common_site_config_path)
    update_site_config("erpnext_support_password",
                       password,
                       site_config_path=common_site_config_path)

    return json.dumps({"user": user, "password": password})
示例#29
0
def setup_global_help(mariadb_root_password=None):
	'''setup help table in a separate database that will be
	shared by the whole bench and set `global_help_setup` as 1 in
	common_site_config.json'''

	from frappe.installer import update_site_config

	frappe.local.flags = frappe._dict()
	frappe.local.flags.in_setup_help = True
	frappe.local.flags.in_install = True
	frappe.local.lang = 'en'
	frappe.local.conf = frappe.get_site_config(sites_path='.')

	update_site_config('global_help_setup', 1,
		site_config_path=os.path.join('.', 'common_site_config.json'))

	if mariadb_root_password:
		frappe.local.conf.root_password = mariadb_root_password

	from frappe.utils.help import sync
	sync()
示例#30
0
def create_support_user():
    url = frappe.conf.erpnext_support_url
    user = frappe.conf.erpnext_support_user
    password = frappe.conf.erpnext_support_password

    if not url:
        common_site_config_path = os.path.join(frappe.utils.get_bench_path(),
                                               "sites",
                                               "common_site_config.json")
        url = "https://frappe.erpnext.com"
        update_site_config("erpnext_support_url",
                           url,
                           site_config_path=common_site_config_path)

    if not (user and password):
        user = "******" + frappe.utils.random_string(
            8) + "@erpnext.com"
        password = frappe.utils.random_string(16)

        params = {
            "cmd": "erpnext_support.api.server.make_support_user",
            "user": user,
            "password": password
        }

        r = FrappeClient(url)
        res = json.loads(r.post_request(params))

        if res:
            common_site_config_path = os.path.join(
                frappe.utils.get_bench_path(), "sites",
                "common_site_config.json")
            update_site_config("erpnext_support_user",
                               res.get("user"),
                               site_config_path=common_site_config_path)
            update_site_config("erpnext_support_password",
                               res.get("password"),
                               site_config_path=common_site_config_path)
示例#31
0
def create_rq_users(set_admin_password=False, use_rq_auth=False):
	"""Create Redis Queue users and add to acl and app configs.

	acl config file will be used by redis server while starting the server
	and app config is used by app while connecting to redis server.
	"""
	acl_file_path = os.path.abspath('../config/redis_queue.acl')

	with frappe.init_site():
		acl_list, user_credentials = RedisQueue.gen_acl_list(
			set_admin_password=set_admin_password)

	with open(acl_file_path, 'w') as f:
		f.writelines([acl+'\n' for acl in acl_list])

	sites_path = os.getcwd()
	common_site_config_path = os.path.join(sites_path, 'common_site_config.json')
	update_site_config("rq_username", user_credentials['bench'][0], validate=False,
		site_config_path=common_site_config_path)
	update_site_config("rq_password", user_credentials['bench'][1], validate=False,
		site_config_path=common_site_config_path)
	update_site_config("use_rq_auth", use_rq_auth, validate=False,
		site_config_path=common_site_config_path)

	click.secho('* ACL and site configs are updated with new user credentials. '
		'Please restart Redis Queue server to enable namespaces.',
		fg='green')

	if set_admin_password:
		env_key = 'RQ_ADMIN_PASWORD'
		click.secho('* Redis admin password is successfully set up. '
			'Include below line in .bashrc file for system to use',
			fg='green')
		click.secho(f"`export {env_key}={user_credentials['default'][1]}`")
		click.secho('NOTE: Please save the admin password as you '
			'can not access redis server without the password',
			fg='yellow')
示例#32
0
def activate_scheduler():
    if is_scheduler_disabled():
        enable_scheduler()
    if frappe.conf.pause_scheduler:
        update_site_config('pause_scheduler', 0)
示例#33
0
def restrict_scheduler_events_if_dormant():
	if is_dormant():
		restrict_scheduler_events()
		update_site_config('dormant', True)
示例#34
0
def update_limits(limits_dict):
    """Add/Update limit in site_config"""
    limits = get_limits()
    limits.update(limits_dict)
    update_site_config("limits", limits, validate=False)
    frappe.conf.limits = limits
	if len(pwd) > 100:
		# encrypting > 100 chars will lead to truncation
		frappe.throw(_('Password cannot be more than 100 characters long'))

	cipher_suite = Fernet(encode(get_encryption_key()))
	cipher_text = cstr(cipher_suite.encrypt(encode(pwd)))
	return cipher_text

def decrypt(pwd):
	try:
		cipher_suite = Fernet(encode(get_encryption_key()))
		plain_text = cstr(cipher_suite.decrypt(encode(pwd)))
		return plain_text
	except InvalidToken:
		# encryption_key in site_config is changed and not valid
		frappe.throw(_('Encryption key is invalid, Please check site_config.json'))

def get_encryption_key():
	from frappe.installer import update_site_config

	if 'encryption_key' not in frappe.local.conf:
<<<<<<< HEAD
		encryption_key = Fernet.generate_key()
=======
		encryption_key = Fernet.generate_key().decode()
>>>>>>> 176d241496ede1357a309fa44a037b757a252581
		update_site_config('encryption_key', encryption_key)
		frappe.local.conf.encryption_key = encryption_key

	return frappe.local.conf.encryption_key
示例#36
0
def restore_database(files_base, site_config_path, site):
    db_root_password = get_password('MYSQL_ROOT_PASSWORD')
    if not db_root_password:
        print('Variable MYSQL_ROOT_PASSWORD not set')
        exit(1)

    db_root_user = os.environ.get("DB_ROOT_USER", 'root')

    # restore database
    database_file = files_base + '-database.sql.gz'
    decompress_db(files_base, site)
    config = get_config()
    site_config = get_site_config(site)

    # mysql command prefix
    mysql_command = 'mysql -u{db_root_user} -h{db_host} -p{db_password} -e '.format(
        db_root_user=db_root_user,
        db_host=config.get('db_host'),
        db_password=db_root_password)

    # drop db if exists for clean restore
    drop_database = mysql_command + "\"DROP DATABASE IF EXISTS \`{db_name}\`;\"".format(
        db_name=site_config.get('db_name'))
    os.system(drop_database)

    # create db
    create_database = mysql_command + "\"CREATE DATABASE IF NOT EXISTS \`{db_name}\`;\"".format(
        db_name=site_config.get('db_name'))
    os.system(create_database)

    # create user
    create_user = mysql_command + "\"CREATE USER IF NOT EXISTS \'{db_name}\'@\'%\' IDENTIFIED BY \'{db_password}\'; FLUSH PRIVILEGES;\"".format(
        db_name=site_config.get('db_name'),
        db_password=site_config.get('db_password'))
    os.system(create_user)

    # grant db privileges to user
    grant_privileges = mysql_command + "\"GRANT ALL PRIVILEGES ON \`{db_name}\`.* TO '{db_name}'@'%' IDENTIFIED BY '{db_password}'; FLUSH PRIVILEGES;\"".format(
        db_name=site_config.get('db_name'),
        db_password=site_config.get('db_password'))
    os.system(grant_privileges)

    command = "mysql -u{db_root_user} -h{db_host} -p{db_password} '{db_name}' < {database_file}".format(
        db_root_user=db_root_user,
        db_host=config.get('db_host'),
        db_password=db_root_password,
        db_name=site_config.get('db_name'),
        database_file=database_file.replace('.gz', ''),
    )

    print('Restoring database for site: {}'.format(site))
    os.system(command)

    if os.path.exists(site_config_path):
        with open(site_config_path, 'r') as sc:
            site_config = json.load(sc)
        encryption_key = site_config.get("encryption_key")
        if encryption_key:
            print('Restoring site config for site: {}'.format(site))
            update_site_config('encryption_key',
                               encryption_key,
                               site_config_path=os.path.join(
                                   os.getcwd(), site, "site_config.json"))
示例#37
0
文件: new.py 项目: ektai/erp
def main():
    config = get_config()
    db_type = 'mariadb'
    db_port = config.get('db_port', 3306)
    db_host = config.get('db_host')
    site_name = os.environ.get("SITE_NAME", 'site1.localhost')
    db_root_username = os.environ.get("DB_ROOT_USER", 'root')
    mariadb_root_password = get_password("MYSQL_ROOT_PASSWORD", 'admin')
    postgres_root_password = get_password("POSTGRES_PASSWORD")
    db_root_password = mariadb_root_password

    if postgres_root_password:
        db_type = 'postgres'
        db_host = os.environ.get("POSTGRES_HOST")
        db_port = 5432
        db_root_password = postgres_root_password
        if not db_host:
            db_host = config.get('db_host')
            print('Environment variable POSTGRES_HOST not found.')
            print('Using db_host from common_site_config.json')

        sites_path = os.getcwd()
        common_site_config_path = os.path.join(sites_path,
                                               COMMON_SITE_CONFIG_FILE)
        update_site_config("root_login",
                           db_root_username,
                           validate=False,
                           site_config_path=common_site_config_path)
        update_site_config("root_password",
                           db_root_password,
                           validate=False,
                           site_config_path=common_site_config_path)

    force = True if os.environ.get("FORCE", None) else False
    install_apps = os.environ.get("INSTALL_APPS", None)
    install_apps = install_apps.split(',') if install_apps else []
    frappe.init(site_name, new_site=True)

    if semantic_version.Version(frappe.__version__).major > 11:
        _new_site(
            None,
            site_name,
            mariadb_root_username=db_root_username,
            mariadb_root_password=db_root_password,
            admin_password=get_password("ADMIN_PASSWORD", 'admin'),
            verbose=True,
            install_apps=install_apps,
            source_sql=None,
            force=force,
            db_type=db_type,
            reinstall=False,
            db_host=db_host,
            db_port=db_port,
        )
    else:
        _new_site(
            None,
            site_name,
            mariadb_root_username=db_root_username,
            mariadb_root_password=db_root_password,
            admin_password=get_password("ADMIN_PASSWORD", 'admin'),
            verbose=True,
            install_apps=install_apps,
            source_sql=None,
            force=force,
            reinstall=False,
        )

    if db_type == "mariadb":
        site_config = get_site_config(site_name)
        db_name = site_config.get('db_name')
        db_password = site_config.get('db_password')

        mysql_command = [
            "mysql", f"-h{db_host}", f"-u{db_root_username}",
            f"-p{mariadb_root_password}", "-e"
        ]

        # Drop User if exists
        command = mysql_command + [
            f"DROP USER IF EXISTS '{db_name}'; FLUSH PRIVILEGES;"
        ]
        run_command(command)

        # Grant permission to database and set password
        grant_privileges = "ALL PRIVILEGES"

        # for Amazon RDS
        if config.get(RDS_DB) or site_config.get(RDS_DB):
            grant_privileges = RDS_PRIVILEGES

        command = mysql_command + [
            f"\
            CREATE USER IF NOT EXISTS '{db_name}'@'%' IDENTIFIED BY '{db_password}'; \
            GRANT {grant_privileges} ON `{db_name}`.* TO '{db_name}'@'%'; \
            FLUSH PRIVILEGES;"
        ]
        run_command(command)

    if frappe.redis_server:
        frappe.redis_server.connection_pool.disconnect()

    exit(0)
示例#38
0
def main():
    config = get_config()
    db_type = 'mariadb'
    db_port = config.get('db_port', 3306)
    db_host = config.get('db_host')
    site_name = os.environ.get("SITE_NAME", 'site1.localhost')
    mariadb_root_username = os.environ.get("DB_ROOT_USER", 'root')
    mariadb_root_password = get_password("MYSQL_ROOT_PASSWORD", 'admin')
    postgres_root_password = get_password("POSTGRES_PASSWORD")

    if postgres_root_password:
        db_type = 'postgres'
        db_host = os.environ.get("POSTGRES_HOST")
        db_port = 5432
        if not db_host:
            db_host = config.get('db_host')
            print('Environment variable POSTGRES_HOST not found.')
            print('Using db_host from common_site_config.json')

        sites_path = os.getcwd()
        common_site_config_path = os.path.join(sites_path,
                                               COMMON_SITE_CONFIG_FILE)
        update_site_config("root_login",
                           mariadb_root_username,
                           validate=False,
                           site_config_path=common_site_config_path)
        update_site_config("root_password",
                           postgres_root_password,
                           validate=False,
                           site_config_path=common_site_config_path)

    force = True if os.environ.get("FORCE", None) else False
    install_apps = os.environ.get("INSTALL_APPS", None)
    install_apps = install_apps.split(',') if install_apps else []
    frappe.init(site_name, new_site=True)

    if semantic_version.Version(frappe.__version__).major > 11:
        _new_site(
            None,
            site_name,
            mariadb_root_username=mariadb_root_username,
            mariadb_root_password=mariadb_root_password,
            admin_password=get_password("ADMIN_PASSWORD", 'admin'),
            verbose=True,
            install_apps=install_apps,
            source_sql=None,
            force=force,
            db_type=db_type,
            reinstall=False,
            db_host=db_host,
            db_port=db_port,
        )
    else:
        _new_site(
            None,
            site_name,
            mariadb_root_username=mariadb_root_username,
            mariadb_root_password=mariadb_root_password,
            admin_password=get_password("ADMIN_PASSWORD", 'admin'),
            verbose=True,
            install_apps=install_apps,
            source_sql=None,
            force=force,
            reinstall=False,
        )

    if db_type == "mariadb":
        site_config = get_site_config(site_name)

        mysql_command = 'mysql -h{db_host} -u{mariadb_root_username} -p{mariadb_root_password} -e '.format(
            db_host=config.get('db_host'),
            mariadb_root_username=mariadb_root_username,
            mariadb_root_password=mariadb_root_password)

        # update User's host to '%' required to connect from any container
        command = mysql_command + "\"UPDATE mysql.user SET Host = '%' where User = '******'; FLUSH PRIVILEGES;\"".format(
            db_name=site_config.get('db_name'))
        os.system(command)

        # Set db password
        command = mysql_command + "\"ALTER USER '{db_name}'@'%' IDENTIFIED BY '{db_password}'; FLUSH PRIVILEGES;\"".format(
            db_name=site_config.get('db_name'),
            db_password=site_config.get('db_password'))
        os.system(command)

        # Grant permission to database
        command = mysql_command + "\"GRANT ALL PRIVILEGES ON \`{db_name}\`.* TO '{db_name}'@'%'; FLUSH PRIVILEGES;\"".format(
            db_name=site_config.get('db_name'))
        os.system(command)

    if frappe.redis_server:
        frappe.redis_server.connection_pool.disconnect()

    exit(0)
示例#39
0
def restrict_scheduler_events_if_dormant():
    if is_dormant():
        restrict_scheduler_events()
        update_site_config('dormant', True)
示例#40
0
def restore_postgres(config, site_config, database_file):
    # common config
    common_site_config_path = os.path.join(os.getcwd(),
                                           COMMON_SITE_CONFIG_FILE)

    db_root_user = config.get('root_login')
    if not db_root_user:
        postgres_user = os.environ.get('DB_ROOT_USER')
        if not postgres_user:
            print('Variable DB_ROOT_USER not set')
            exit(1)

        db_root_user = postgres_user
        update_site_config("root_login",
                           db_root_user,
                           validate=False,
                           site_config_path=common_site_config_path)

    db_root_password = config.get('root_password')
    if not db_root_password:
        root_password = get_password('POSTGRES_PASSWORD')
        if not root_password:
            print('Variable POSTGRES_PASSWORD not set')
            exit(1)

        db_root_password = root_password
        update_site_config("root_password",
                           db_root_password,
                           validate=False,
                           site_config_path=common_site_config_path)

    # site config
    db_host = site_config.get('db_host')
    db_port = site_config.get('db_port', 5432)
    db_name = site_config.get('db_name')
    db_password = site_config.get('db_password')

    psql_command = "psql postgres://{root_login}:{root_password}@{db_host}:{db_port}".format(
        root_login=db_root_user,
        root_password=db_root_password,
        db_host=db_host,
        db_port=db_port)

    print('Restoring PostgreSQL')
    os.system(psql_command +
              ' -c "DROP DATABASE IF EXISTS \"{db_name}\""'.format(
                  db_name=db_name))
    os.system(psql_command +
              ' -c "DROP USER IF EXISTS {db_name}"'.format(db_name=db_name))
    os.system(psql_command +
              ' -c "CREATE DATABASE \"{db_name}\""'.format(db_name=db_name))
    os.system(psql_command +
              ' -c "CREATE user {db_name} password \'{db_password}\'"'.format(
                  db_name=db_name, db_password=db_password))
    os.system(
        psql_command +
        ' -c "GRANT ALL PRIVILEGES ON DATABASE \"{db_name}\" TO {db_name}"'.
        format(db_name=db_name))

    os.system("{psql_command}/{db_name} < {database_file}".format(
        psql_command=psql_command,
        database_file=database_file.replace('.gz', ''),
        db_name=db_name,
    ))