def perform_config_replacements (root): path = os.path.join (root, 'phpMyAdmin', 'config.inc.php') pre = "tmp!market!install!db" dbname = CTK.cfg.get_val('%s!db_name' %(pre)) dbuser = CTK.cfg.get_val('%s!db_user' %(pre)) dbpass = CTK.cfg.get_val('%s!db_pass' %(pre)) options = string.letters + string.digits secret = "" for i in range(80): secret += random.choice(options) config = open (path, 'r').read() config = config.replace('${pmadb}', dbname) config = config.replace('${pmauser}', dbuser) config = config.replace('${pmapass}', dbpass) config = config.replace('${blowfish_secret}', secret) config = config.replace('${upload_dir}', os.path.join (root, 'dir_upload')) config = config.replace('${save_dir}', os.path.join (root, 'dir_save')) try: open (path, 'w').write(config) Install_Log.log ("Success: config.inc.php customized") except: Install_Log.log ("Error: config.inc.php not customized") raise
def preload_installer(root): path = os.path.join(root, 'drupal', 'install.php') pre = "tmp!market!install!db" dbtype = CTK.cfg.get_val('%s!db_type' % (pre)) dbname = CTK.cfg.get_val('%s!db_name' % (pre)) dbuser = CTK.cfg.get_val('%s!db_user' % (pre)) dbpass = CTK.cfg.get_val('%s!db_pass' % (pre)) if dbtype == "postgresql": dbtype = 'pgsql' else: # mysql modules = [x.lower() for x in php.figure_modules()] if 'mysqli' in modules: dbtype = 'mysqli' else: dbtype = 'mysql' subst = [('${dbtype}', dbtype), ('${dbname}', dbname), ('${dbuser}', dbuser), ('${dbpass}', dbpass)] data = open(path, 'r').read() for s in subst: data = data.replace(s[0], s[1]) try: open(path, 'w').write(data) Install_Log.log("Success: install.php customized") except: Install_Log.log("Error: install.php not customized") raise
def preload_installer (root): path = os.path.join (root, 'drupal', 'install.php') pre = "tmp!market!install!db" dbtype = CTK.cfg.get_val('%s!db_type' %(pre)) dbname = CTK.cfg.get_val('%s!db_name' %(pre)) dbuser = CTK.cfg.get_val('%s!db_user' %(pre)) dbpass = CTK.cfg.get_val('%s!db_pass' %(pre)) if dbtype == "postgresql": dbtype = 'pgsql' else: # mysql modules = [x.lower() for x in php.figure_modules()] if 'mysqli' in modules: dbtype = 'mysqli' else: dbtype = 'mysql' subst = [('${dbtype}', dbtype), ('${dbname}', dbname), ('${dbuser}', dbuser), ('${dbpass}', dbpass)] data = open(path, 'r').read() for s in subst: data = data.replace (s[0], s[1]) try: open(path, 'w').write(data) Install_Log.log ("Success: install.php customized") except: Install_Log.log ("Error: install.php not customized") raise
def perform_config_replacements(root): path = os.path.join(root, 'phpMyAdmin', 'config.inc.php') pre = "tmp!market!install!db" dbname = CTK.cfg.get_val('%s!db_name' % (pre)) dbuser = CTK.cfg.get_val('%s!db_user' % (pre)) dbpass = CTK.cfg.get_val('%s!db_pass' % (pre)) options = string.letters + string.digits secret = "" for i in range(80): secret += random.choice(options) config = open(path, 'r').read() config = config.replace('${pmadb}', dbname) config = config.replace('${pmauser}', dbuser) config = config.replace('${pmapass}', dbpass) config = config.replace('${blowfish_secret}', secret) config = config.replace('${upload_dir}', os.path.join(root, 'dir_upload')) config = config.replace('${save_dir}', os.path.join(root, 'dir_save')) try: open(path, 'w').write(config) Install_Log.log("Success: config.inc.php customized") except: Install_Log.log("Error: config.inc.php not customized") raise
def set_default_settings (): pre = "tmp!market!install" root = CTK.cfg.get_val ('%s!root' %(pre)) dbname = CTK.cfg.get_val('%s!db!db_name' %(pre)) dbuser = CTK.cfg.get_val('%s!db!db_user' %(pre)) dbpass = CTK.cfg.get_val('%s!db!db_pass' %(pre)) path = os.path.join (root, 'vanilla', 'conf', 'config-defaults.php') file = open (path, 'r').read() src = "$Configuration['Database']['Host'] = 'dbhost';" dst = "$Configuration['Database']['Host'] = 'localhost';" file = file.replace(src, dst) src = "$Configuration['Database']['Name'] = 'dbname';" dst = "$Configuration['Database']['Name'] = '%s';" %(dbname) file = file.replace(src, dst) src = "$Configuration['Database']['User'] = '******';" dst = "$Configuration['Database']['User'] = '******';" %(dbuser) file = file.replace(src, dst) src = "$Configuration['Database']['Password'] = '';" dst = "$Configuration['Database']['Password'] = '******';" %(dbpass) file = file.replace(src, dst) src = "$Configuration['Garden']['RewriteUrls'] = FALSE;" dst = "$Configuration['Garden']['RewriteUrls'] = TRUE;" file = file.replace(src, dst) try: open (path, 'w').write (file) Install_Log.log ('Success: config-defaults.php modified.') except: Install_Log.log ('Error: config-defaults.php not modified.') raise
def php_installer_replacements (): """Replace macros patched into the installer""" pre = "tmp!market!install" root = CTK.cfg.get_val ('%s!root' %(pre)) dbtype = CTK.cfg.get_val('%s!db!db_type' %(pre)) dbname = CTK.cfg.get_val('%s!db!db_name' %(pre)) dbuser = CTK.cfg.get_val('%s!db!db_user' %(pre)) dbpass = CTK.cfg.get_val('%s!db!db_pass' %(pre)) if dbtype == 'postgresql': dbtype = 'pgsql' path = os.path.join (root, 'statusnet', 'install.php') file = open (path, 'r').read() file = file.replace('${dbname}', dbname) file = file.replace('${dbuser}', dbuser) file = file.replace('${dbpass}', dbpass) file = file.replace('${dbtype}', dbtype) try: open (path, 'w').write (file) Install_Log.log ('Success: install.php modified.') except: Install_Log.log ('Error: install.php not modified.') raise return {'retcode':0}
def _exe(cmd, error_msg): Install_Log.log(" %s" % (cmd)) ret = popen.popen_sync(cmd) if ret['retcode']: Install_Log.log(" ERROR: %s" % (error_msg)) ret['command'] = cmd ret['error'] = error_msg return ret
def _exe(cmd, error_msg): Install_Log.log(" %s" % (cmd)) ret = popen.popen_sync(cmd) if ret["retcode"]: Install_Log.log(" ERROR: %s" % (error_msg)) ret["command"] = cmd ret["error"] = error_msg return ret
def create_user (self): """Create the database user that is set as property of the object.""" cmd = """psql --command="CREATE USER %(db_user)s WITH PASSWORD '%(db_pass)s'" """%(self.__dict__) ret = run (self._cmd_auth (cmd, self.admin_user, self.admin_pass)) if ret['retcode']: Install_Log.log ("DB: Problem creating PostgreSQL user %s" %(self.db_user)) return stderr_to_error (ret['stderr']) Install_Log.log ("DB: Created PostgreSQL user %s" %(self.db_user))
def Wiki_Config_Replacements (params): path = os.path.join (params['root'], 'moin', 'wikiconfig.py') config = open (path, 'r').read() url_prefix_static = '/moin_static' if params.get('target_directory'): url_prefix_static = os.path.join (params['target_directory'], url_prefix_static) config = config.replace('#${url_prefix_static}', 'url_prefix_static = "%s"' %(url_prefix_static)) config = config.replace('#${sitename}', 'sitename = u"%(sitename)s"' %(params)) config = config.replace('#${superuser}', 'superuser = [u"%(user)s", ]' %(params)) config = config.replace('#${acl_rights_before}', 'acl_rights_before = u"%(user)s:read,write,delete,revert,admin"' %(params)) try: open (path, 'w').write(config) Install_Log.log ('Success: wikiconfig.py modified.') except: Install_Log.log ('Error: wikiconfig.py not modified.') raise server_user = CTK.cfg.get_val ('server!user', str(os.getuid())) server_group = CTK.cfg.get_val ('server!group', str(os.getgid())) root = params['root'] ret = popen.popen_sync ('chown -R %(server_user)s:%(server_group)s %(root)s/moin' %(locals())) if ret['retcode']: Install_Log.log ('Error: Moin permissions not correctly set.') raise ret['stderr'] Install_Log.log ('Success: Moin permissions correctly set.')
def Write_Local_Settings(root, port): local_settings = LOCAL_SETTINGS % (port) server_user = CTK.cfg.get_val('server!user') server_group = CTK.cfg.get_val('server!group') if server_user: local_settings += " user = '******'\n" % (server_user) if server_user: local_settings += " group = '%s'\n" % (server_group) path = os.path.join(root, 'moin', 'wikiserverconfig_local.py') try: open(path, 'w').write(local_settings) Install_Log.log('Local Settings written successfully.') except: Install_Log.log('ERROR: writing Local Settings.') raise
def Write_Local_Settings (root, port): local_settings = LOCAL_SETTINGS %(port) server_user = CTK.cfg.get_val ('server!user') server_group = CTK.cfg.get_val ('server!group') if server_user: local_settings += " user = '******'\n" %(server_user) if server_user: local_settings += " group = '%s'\n" %(server_group) path = os.path.join (root, 'moin', 'wikiserverconfig_local.py') try: open (path, 'w').write (local_settings) Install_Log.log ('Local Settings written successfully.') except: Install_Log.log ('ERROR: writing Local Settings.') raise
def create (self): """Create the database. The values for creation are set as properties of the object.""" # Create the user ret = self.create_user() if ret: return ret # Create the database cmd = "createdb '%(db_name)s' --encoding=utf8 --owner='%(db_user)s'" %(self.__dict__) ret = run (self._cmd_auth (cmd, self.admin_user, self.admin_pass)) if ret['retcode']: Install_Log.log ("DB: Problem creating PostgreSQL database %s" %(self.db_name)) return stderr_to_error (ret['stderr']) Install_Log.log ("DB: Created PostgreSQL database %s" %(self.db_name))
def _exe(cmd, error_msg): """Wrap system calls, adding a reference to the executed command and possible error message to the returned value. exe() returns a dictionary with the following keys: command: command retcode: return code of the execution of specified command. 0 on success. error: error message stdout: standard output of execution stderr: error buffer of execution""" Install_Log.log(" %s" % (cmd)) ret = popen.popen_sync(cmd) if ret['retcode']: Install_Log.log(" ERROR: %s" % (error_msg)) ret['command'] = cmd ret['error'] = error_msg return ret
def create_pmadb (root): path = os.path.join (root, 'phpMyAdmin', 'scripts', 'create_tables.sql') pre = "tmp!market!install!db" dbname = CTK.cfg.get_val('%s!db_name' %(pre)) dbuser = CTK.cfg.get_val('%s!db_user' %(pre)) dbpass = CTK.cfg.get_val('%s!db_pass' %(pre)) sql = open(path, 'r').read() sql = sql.replace (SOURCE_SQL, TARGET_SQL %(locals())) try: open (path, 'w').write(sql) except: Install_Log.log ("Error: template for pmadb structure not created.") raise mysql_bin = database.mysql_bins (database.MYSQL_BIN_NAMES) if dbpass: ret = popen.popen_sync ('%(mysql_bin)s -u%(dbuser)s -p%(dbpass)s < %(path)s' %(locals())) else: ret = popen.popen_sync ('%(mysql_bin)s -u%(dbuser)s < %(path)s' %(locals())) if ret['retcode']: Install_Log.log ("Error: pmadb structure not created.") raise EnvironmentError, ret['stderr'] else: Install_Log.log ("Success: pmadb structure created.")
def create_pmadb(root): path = os.path.join(root, 'phpMyAdmin', 'scripts', 'create_tables.sql') pre = "tmp!market!install!db" dbname = CTK.cfg.get_val('%s!db_name' % (pre)) dbuser = CTK.cfg.get_val('%s!db_user' % (pre)) dbpass = CTK.cfg.get_val('%s!db_pass' % (pre)) sql = open(path, 'r').read() sql = sql.replace(SOURCE_SQL, TARGET_SQL % (locals())) try: open(path, 'w').write(sql) except: Install_Log.log("Error: template for pmadb structure not created.") raise mysql_bin = database.mysql_bins(database.MYSQL_BIN_NAMES) if dbpass: ret = popen.popen_sync( '%(mysql_bin)s -u%(dbuser)s -p%(dbpass)s < %(path)s' % (locals())) else: ret = popen.popen_sync('%(mysql_bin)s -u%(dbuser)s < %(path)s' % (locals())) if ret['retcode']: Install_Log.log("Error: pmadb structure not created.") raise EnvironmentError, ret['stderr'] else: Install_Log.log("Success: pmadb structure created.")
def check_privileges (self, privs): """Ensure the specified privileges are granted for this user/password/database combination. Returns an error otherwise.""" to_check = [] # Accepted privileges for has_database_privilege: CREATE, CONNECT, TEMPORARY, TEMP for priv in privs: if priv in ['create_table', 'write']: if not 'CREATE' in to_check: to_check.append ('CREATE') elif priv == 'read': to_check.append ('CONNECT') else: raise ValueError, '%s: %s' %(_('Unknown privilege'), priv) # Check missing_privs = [] for priv in to_check: cmd = """psql --list --tuples-only --no-align --command="SELECT has_database_privilege ('%s', '%s');" """ %(self.db_name, priv) ret = run (self._cmd_auth (cmd, self.db_user, self.db_pass)) if ret['retcode']: Install_Log.log ("DB: Error checking PostgreSQL privilege: %s" %(priv)) return stderr_to_error (ret['stderr']) if 'f' in ret['stdout']: missing_privs.append (priv) if missing_privs: Install_Log.log ("DB: Unsuccessfull PostgreSQL privilege check: %s" %(', '.join(missing_privs))) msg = _('User %(db_user)s is missing the following privileges on database %(db_name)s') %(params) return '%s: %s' %(msg, ', '.join(missing_privs)) Install_Log.log ("DB: Successfull PostgreSQL privilege check")
def modify_installer (root): path = os.path.join (root, 'silverstripe', 'install.php') pre = "tmp!market!install!db" dbtype = CTK.cfg.get_val('%s!db_type' %(pre)) dbname = CTK.cfg.get_val('%s!db_name' %(pre)) dbuser = CTK.cfg.get_val('%s!db_user' %(pre)) dbpass = CTK.cfg.get_val('%s!db_pass' %(pre)) installer = open(path, 'r').read() installer = installer.replace('SS_DATABASE_USERNAME : "******"', 'SS_DATABASE_USERNAME : "******"'%(dbuser)) installer = installer.replace('SS_DATABASE_PASSWORD : ""', 'SS_DATABASE_PASSWORD : "******"'%(dbpass)) installer = installer.replace('"SS_mysite"', '"%s"'%(dbname)) try: open(path, 'w').write(installer) Install_Log.log ("Success: install.php customized") except: Install_Log.log ("Error: install.php not customized") return False return True
def create (self): """Create the database. The values for creation are set as properties of the object.""" # Create the database params = self.__dict__.copy() params['mysql_bin'] = mysql_bins(MYSQL_BIN_NAMES) params['mysqladmin_bin'] = mysql_bins(MYSQLADMIN_BIN_NAMES) if self.admin_pass: cmd = "%(mysqladmin_bin)s '-u%(admin_user)s' '-p%(admin_pass)s' create '%(db_name)s' --default-character-set=utf8" %(params) else: cmd = "%(mysqladmin_bin)s '-u%(admin_user)s' create '%(db_name)s' --default-character-set=utf8" %(params) ret = run (cmd) if ret['retcode']: return stderr_to_error (ret['stderr']) Install_Log.log ("DB: Created MySQL database %s" %(self.db_name)) # Modify collation and grant permissions if self.admin_pass: cmd = "%(mysql_bin)s '-u%(admin_user)s' '-p%(admin_pass)s' << EOF\n" %(params) else: cmd = "%(mysql_bin)s '-u%(admin_user)s' << EOF\n" %(params) sql = """ALTER DATABASE %(db_name)s DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;\nEOF\n""" %(params) ret = run (cmd + sql) if ret['retcode'] == 0: Install_Log.log ("DB: Modified collation on %s" %(self.db_name)) sql = """GRANT ALL PRIVILEGES ON %(db_name)s.* TO %(db_user)s@localhost IDENTIFIED BY '%(db_pass)s'; FLUSH PRIVILEGES;\nEOF\n""" %(params) ret = run (cmd + sql) if ret['retcode'] == 0: Install_Log.log ("DB: Granted privileges on %s to user %s" %(self.db_name, self.db_user)) return # Drop DB if it could not set the permissions Install_Log.log ("DB: Deleted MySQL database %s" %(self.db_name)) if self.admin_pass: cmd = "%(mysqladmin_bin)s --force '-u%(admin_user)s' '-p%(admin_pass)s' drop '%(db_name)s'" %(params) else: cmd = "%(mysqladmin_bin)s --force '-u%(admin_user)s' drop '%(db_name)s'" %(params) run (cmd) # Report the 'Grant permissions' error return stderr_to_error (ret['stderr'])
def modify_installer(root): path = os.path.join(root, 'silverstripe', 'install.php') pre = "tmp!market!install!db" dbtype = CTK.cfg.get_val('%s!db_type' % (pre)) dbname = CTK.cfg.get_val('%s!db_name' % (pre)) dbuser = CTK.cfg.get_val('%s!db_user' % (pre)) dbpass = CTK.cfg.get_val('%s!db_pass' % (pre)) installer = open(path, 'r').read() installer = installer.replace('SS_DATABASE_USERNAME : "******"', 'SS_DATABASE_USERNAME : "******"' % (dbuser)) installer = installer.replace('SS_DATABASE_PASSWORD : ""', 'SS_DATABASE_PASSWORD : "******"' % (dbpass)) installer = installer.replace('"SS_mysite"', '"%s"' % (dbname)) try: open(path, 'w').write(installer) Install_Log.log("Success: install.php customized") except: Install_Log.log("Error: install.php not customized") return False return True
def Wiki_Config_Replacements(params): path = os.path.join(params['root'], 'moin', 'wikiconfig.py') config = open(path, 'r').read() url_prefix_static = '/moin_static' if params.get('target_directory'): url_prefix_static = os.path.join(params['target_directory'], url_prefix_static) config = config.replace('#${url_prefix_static}', 'url_prefix_static = "%s"' % (url_prefix_static)) config = config.replace('#${sitename}', 'sitename = u"%(sitename)s"' % (params)) config = config.replace('#${superuser}', 'superuser = [u"%(user)s", ]' % (params)) config = config.replace( '#${acl_rights_before}', 'acl_rights_before = u"%(user)s:read,write,delete,revert,admin"' % (params)) try: open(path, 'w').write(config) Install_Log.log('Success: wikiconfig.py modified.') except: Install_Log.log('Error: wikiconfig.py not modified.') raise server_user = CTK.cfg.get_val('server!user', str(os.getuid())) server_group = CTK.cfg.get_val('server!group', str(os.getgid())) root = params['root'] ret = popen.popen_sync( 'chown -R %(server_user)s:%(server_group)s %(root)s/moin' % (locals())) if ret['retcode']: Install_Log.log('Error: Moin permissions not correctly set.') raise ret['stderr'] Install_Log.log('Success: Moin permissions correctly set.')
def check_privileges (self, privs): """Ensure the specified privileges are granted for this user/password/database combination. Returns an error otherwise.""" to_check = [] for priv in privs: if priv == 'create_table': to_check.append ('CREATE') elif priv == 'write': to_check.append ('INSERT') elif priv == 'read': to_check.append ('SELECT') else: raise ValueError, '%s: %s' %(_('Unknown privilege'), priv) # Build command params = self.__dict__.copy() params['sql'] = "SELECT privilege_type FROM schema_privileges WHERE table_schema='%(db_name)s';" %(params) params['bin'] = mysql_bins (MYSQL_BIN_NAMES) if params.get('db_user'): cmd = """%(bin)s '-u%(db_user)s' '-p%(db_pass)s' 'information_schema' -s -e "%(sql)s" """ else: cmd = """%(bin)s '-u%(db_user)s' 'information_schema' -s -e "%(sql)s" """ cmd = cmd%(params) # Execute it ret = run (cmd) if ret['retcode']: Install_Log.log ("DB: Error checking MySQL privileges") return stderr_to_error (ret['stderr']) # Check provided_privs = ret['stdout'].splitlines() missing_privs = [] for priv in to_check: if not priv in provided_privs: missing_privs.append (priv) if missing_privs: Install_Log.log ("DB: Unsuccessfull MySQL privilege check: %s" %(', '.join(missing_privs))) msg = _('User %(db_user)s is missing the following privileges on database %(db_name)s') %(params) return '%s: %s' %(msg, ', '.join(missing_privs)) Install_Log.log ("DB: Successfull MySQL privilege check")
def Wiki_Details_Apply(): pre = 'tmp!market!install' user = CTK.post.get_val("%s!user" % (pre)) password = CTK.post.get_val("%s!password" % (pre)) root = CTK.cfg.get_val('%s!root' % (pre)) env = os.environ.copy() env['PYTHONPATH'] = os.path.join(root, 'moin') ret = popen.popen_sync(ADD_USER_COMMAND % (locals()), stderr=True, env=env) Install_Log.log('Running command: %s' % (ADD_USER_COMMAND % (locals()))) Install_Log.log(' ' + ret['stdout']) if ret['stderr']: Install_Log.log(' ' + ret['stderr']) if not '- created.' in ret['stdout']: return {'ret': 'error', 'errors': {"%s!user" % (pre): _(ERROR_USER)}} ret = CTK.cfg_apply_post() return ret
def Wiki_Details_Apply(): pre = 'tmp!market!install' user = CTK.post.get_val("%s!user"%(pre)) password = CTK.post.get_val("%s!password"%(pre)) root = CTK.cfg.get_val ('%s!root' %(pre)) env = os.environ.copy() env['PYTHONPATH'] = os.path.join(root, 'moin') ret = popen.popen_sync (ADD_USER_COMMAND %(locals()), stderr=True, env=env) Install_Log.log ('Running command: %s' %(ADD_USER_COMMAND %(locals()))) Install_Log.log (' ' + ret['stdout']) if ret['stderr']: Install_Log.log (' ' + ret['stderr']) if not '- created.' in ret['stdout']: return {'ret':'error', 'errors': {"%s!user"%(pre): _(ERROR_USER)}} ret = CTK.cfg_apply_post() return ret
def register_service(service, macos_plist=None): """Register system service so that it is started at boot time. The name of the service should be provided. On MacOS X, an additional Launchd service file must be specified. register_service() returns a dictionary with the following keys: command: command retcode: return code of the execution of specified command. 0 on success. error: error message stdout: standard output of execution stderr: error buffer of execution""" # System info retrival system_info = SystemInfo.get_info() OS = system_info.get("system", "").lower() distro = system_info.get("linux_distro_id", "").lower() # Execute command error_msg = _("Could not add <em>%(service)s</em> to list of system services.") % (locals()) if distro in ("fedora", "redhat", "centos", "suse", "opensuse"): ret = _exe("chkconfig --add %(service)s" % (locals()), error_msg) if ret["retcode"]: return ret ret = _exe("chkconfig %(service)s on" % (locals()), error_msg) if ret["retcode"]: return ret # Log (do not change string, check Maintenance.py) Install_Log.log("Registered system service: %(service)s" % (locals())) return ret elif OS == "linux": cmd = "ln -s /etc/init.d/%(service)s /etc/rcS.d/S99%(service)s" % (locals()) ret = _exe(cmd, error_msg) if ret["retcode"]: return ret # Log (do not change string, check Maintenance.py) Install_Log.log("Registered system service: %(service)s" % (locals())) return ret elif OS == "darwin": assert macos_plist, "Launchd service file not provided" cmd = "launchctl load %(macos_plist)s" % (locals()) ret = _exe(cmd, error_msg) if ret["retcode"]: return ret # Log (do not change string, check Maintenance.py) Install_Log.log("Registered Launchd service: %(macos_plist)s" % (locals())) return ret elif OS == "freebsd": # Find out variable name for rc (coded in init script) cmd = None for path in ("/usr/local/etc/rc.d", "/etc/rc.d"): if os.path.exists("%(path)s/%(service)s" % (locals())) and os.access( "%(path)s/%(service)s" % (locals()), os.X_OK ): cmd = "%(path)s/%(service)s rcvar" % (locals()) assert cmd, "Init script not present on /etc/rc.d or /usr/local/etc/rc.d" ret = _exe(cmd, error_msg) rcvar = re.findall("^([^#].*)=", ret["stdout"], re.M)[0] # Read init file (to add or modify if entry already present) lines = open("/etc/rc.conf", "r").readlines() content = "" for line in lines: if re.findall(r"%(rcvar)s=.+" % (locals()), line): content += '%(rcvar)s="YES"\n' % (locals()) else: content += line if content == "".join(lines): content += '%(rcvar)s="YES"\n' % (locals()) # Write try: open("/etc/rc.conf", "w").write(content) # Log (do not change string, check Maintenance.py) Install_Log.log("Registered BSD service: %(rcvar)s" % (locals())) except: raise return ret assert False, "Unknown platform: %s" % (str(system_info))
def run (cmd, *args, **kwargs): Install_Log.log ("DB: %s" %(cmd)) return popen.popen_sync (cmd, *args, **kwargs)
def register_service(service, macos_plist=None): """Register system service so that it is started at boot time. The name of the service should be provided. On MacOS X, an additional Launchd service file must be specified. register_service() returns a dictionary with the following keys: command: command retcode: return code of the execution of specified command. 0 on success. error: error message stdout: standard output of execution stderr: error buffer of execution""" # System info retrival system_info = SystemInfo.get_info() OS = system_info.get('system', '').lower() distro = system_info.get('linux_distro_id', '').lower() # Execute command error_msg = _( 'Could not add <em>%(service)s</em> to list of system services.') % ( locals()) if distro in ('fedora', 'redhat', 'centos', 'suse', 'opensuse'): ret = _exe('chkconfig --add %(service)s' % (locals()), error_msg) if ret['retcode']: return ret ret = _exe('chkconfig %(service)s on' % (locals()), error_msg) if ret['retcode']: return ret # Log (do not change string, check Maintenance.py) Install_Log.log('Registered system service: %(service)s' % (locals())) return ret elif OS == 'linux': cmd = 'ln -s /etc/init.d/%(service)s /etc/rcS.d/S99%(service)s' % ( locals()) ret = _exe(cmd, error_msg) if ret['retcode']: return ret # Log (do not change string, check Maintenance.py) Install_Log.log('Registered system service: %(service)s' % (locals())) return ret elif OS == 'darwin': assert macos_plist, "Launchd service file not provided" cmd = 'launchctl load %(macos_plist)s' % (locals()) ret = _exe(cmd, error_msg) if ret['retcode']: return ret # Log (do not change string, check Maintenance.py) Install_Log.log('Registered Launchd service: %(macos_plist)s' % (locals())) return ret elif OS == 'freebsd': # Find out variable name for rc (coded in init script) cmd = None for path in ('/usr/local/etc/rc.d', '/etc/rc.d'): if os.path.exists ('%(path)s/%(service)s' %(locals())) and \ os.access ('%(path)s/%(service)s' %(locals()), os.X_OK): cmd = '%(path)s/%(service)s rcvar' % (locals()) assert cmd, "Init script not present on /etc/rc.d or /usr/local/etc/rc.d" ret = _exe(cmd, error_msg) rcvar = re.findall('^([^#].*)=', ret['stdout'], re.M)[0] # Read init file (to add or modify if entry already present) lines = open('/etc/rc.conf', 'r').readlines() content = '' for line in lines: if re.findall(r'%(rcvar)s=.+' % (locals()), line): content += '%(rcvar)s="YES"\n' % (locals()) else: content += line if content == ''.join(lines): content += '%(rcvar)s="YES"\n' % (locals()) # Write try: open('/etc/rc.conf', 'w').write(content) # Log (do not change string, check Maintenance.py) Install_Log.log('Registered BSD service: %(rcvar)s' % (locals())) except: raise return ret assert False, 'Unknown platform: %s' % (str(system_info))