def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) conn = KaresansuiVirtConnection(readonly=False) try: active_networks = conn.list_active_network() inactive_networks = conn.list_inactive_network() if not (opts.name in active_networks or opts.name in inactive_networks): raise KssCommandException( 'Could not find the specified network. - net=%s' % (opts.name)) self.up_progress(10) try: conn.stop_network(opts.name) except KaresansuiVirtException, e: if opt.force is not True: raise KssCommandException( 'Could not stop the specified network. - net=%s' % (opts.name)) self.up_progress(20) try: conn.start_network(opts.name) except KaresansuiVirtException, e: if opts.force is not True: raise KssCommandException( 'Could not start the specified network. - net=%s' % (opts.name)) # try to bring down existing bridge kvn = conn.search_kvn_networks(opts.name)[0] try: bridge_name = kvn.get_info()['bridge']['name'] except KeyError: pass ret, res = execute_command( [NETWORK_IFCONFIG_COMMAND, bridge_name, 'down']) ret, res = execute_command( [NETWORK_BRCTL_COMMAND, 'delbr', bridge_name]) # try again conn.start_network(opts.name)
def do_status(self): retval = {} command_args = [PARSER_COMMAND_ROUTE] (ret,res) = execute_command(command_args) ip_regex = "\d{1,3}(\.\d{1,3}){3}" regex = re.compile("(?P<destination>%s|default)[ \t]+(?P<gateway>%s|\*)[ \t]+(?P<netmask>%s)[ \t]+(?P<flags>[UGH]+)[ \t]+(?P<metric>\d+)[ \t]+(?P<ref>\d+)[ \t]+(?P<use>\d+)[ \t]+(?P<device>[^ ]+)" % (ip_regex,ip_regex,ip_regex,)) for _aline in res: m = regex.match(_aline) if m: device = m.group('device') destination = m.group('destination') if destination == "default": destination = "0.0.0.0" netmask = m.group('netmask') target = "%s/%s" % (destination,netmask,) net = NetworkAddress(target) target = net.cidr try: retval[device] except: retval[device] = {} retval[device][target] = {} for _atype in ["use","metric","ref","flags","gateway"]: try: exec("retval[device][target]['%s'] = m.group('%s')" % (_atype,_atype,)) except: pass return retval
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) delete_command_args = [ ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_NODE, ISCSI_CMD_OPTION_OPERATOR, ISCSI_CMD_OPTION_OPERATOR_DELETE, ISCSI_CMD_OPTION_TARGETNAME, opts.iqn, ] if opts.host: delete_command_args.append(ISCSI_CMD_OPTION_PORTAL) delete_command_args.append(opts.host) (delete_rc, delete_res) = execute_command(delete_command_args) self.up_progress(50) if delete_rc != 0: raise KssCommandException( 'Failed to delete iSCSI. - host=%s iqn=%s message=%s' % (opts.host, opts.iqn, delete_res)) self.logger.info("Delete iSCSI node successful. - host=%s iqn=%s" % (opts.host, opts.iqn)) print >> sys.stdout, _("Delete iSCSI node successful. - host=%s iqn=%s" ) % (opts.host, opts.iqn) return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) logout_command_args = [ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_NODE, ISCSI_CMD_OPTION_TARGETNAME, opts.iqn, ] if opts.host: logout_command_args.append(ISCSI_CMD_OPTION_PORTAL) logout_command_args.append(opts.host) logout_command_args.append(ISCSI_CMD_OPTION_LOGOUT) (logout_rc,logout_res) = execute_command(logout_command_args) self.up_progress(50) if logout_rc != 0: raise KssCommandException('Failed to logout iSCSI. - host=%s iqn=%s message=%s' % (opts.host, opts.iqn, logout_res)) for line in logout_res: if not line: continue self.logger.info("%s" % (line)) print >>sys.stdout, _("%s") % (line) return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) delete_command_args = [ ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_NODE, ISCSI_CMD_OPTION_OPERATOR, ISCSI_CMD_OPTION_OPERATOR_DELETE, ISCSI_CMD_OPTION_TARGETNAME, opts.iqn, ] if opts.host: delete_command_args.append(ISCSI_CMD_OPTION_PORTAL) delete_command_args.append(opts.host) (delete_rc,delete_res) = execute_command(delete_command_args) self.up_progress(50) if delete_rc != 0: raise KssCommandException('Failed to delete iSCSI. - host=%s iqn=%s message=%s' % (opts.host, opts.iqn, delete_res)) self.logger.info("Delete iSCSI node successful. - host=%s iqn=%s" % (opts.host, opts.iqn)) print >>sys.stdout, _("Delete iSCSI node successful. - host=%s iqn=%s") % (opts.host, opts.iqn) return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) logout_command_args = [ ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_NODE, ISCSI_CMD_OPTION_TARGETNAME, opts.iqn, ] if opts.host: logout_command_args.append(ISCSI_CMD_OPTION_PORTAL) logout_command_args.append(opts.host) logout_command_args.append(ISCSI_CMD_OPTION_LOGOUT) (logout_rc, logout_res) = execute_command(logout_command_args) self.up_progress(50) if logout_rc != 0: raise KssCommandException( 'Failed to logout iSCSI. - host=%s iqn=%s message=%s' % (opts.host, opts.iqn, logout_res)) for line in logout_res: if not line: continue self.logger.info("%s" % (line)) print >> sys.stdout, _("%s") % (line) return True
def condrestart(self): ret = 0 if self.status() is True: cmd = [] cmd.append(self._iptables_init) cmd.append('restart') (ret, res) = execute_command(cmd) return ret
def condrestart(self): ret = 0 if self.status() is True: cmd = [] cmd.append(self._iptables_init) cmd.append('restart') (ret,res) = execute_command(cmd) return ret
def detect_config_style(self): retval = PARSER_STATICROUTE_DEFAULT_CONFIG_STYLE command_args = ["grep","ADDRESS\[0\-9\]",PARSER_COMMAND_IFUP_ROUTE] (ret,res) = execute_command(command_args) if ret == 0: retval = "new" glob_str = "%s/%s" % (PARSER_STATICROUTE_DIR,PARSER_STATICROUTE_FILE_PREFIX,) for _afile in glob.glob("%s*" % glob_str): device_name = _afile.replace(glob_str,"") if re.search(r"%s" % self.exclude_device_regex, device_name) is None: command_args = ["grep"," via ",_afile] (ret,res) = execute_command(command_args) if ret == 0: retval = "old" break return retval
def stop(self, force=False): """ <comment-ja> 制御対象サービスを停止する @param self: - @return boolean 成功:True 失敗:False </comment-ja> <comment-en> constructor of class @param self: The object pointer @return: none </comment-en> """ retval = False if force is False: pids = self.status() if force is False and len(pids) == 0: message = "Warning: '%s' already stopped." % (self.service_name, ) self.error_msg.append(message) else: if os.path.exists(self.service_script) and is_executable( self.service_script): command = "%s stop" % (self.service_script, ) command_args = command.split() #print command (ret, res) = execute_command(command_args) time.sleep(self.sleep_time) if force is False: pids = self.status() if force is True or len(pids) == 0: message = "Notice: succeeded to stop '%s'." % ( self.service_name, ) #print message retval = True else: pids = [str(p) for p, q in zip(pids, pids[1:] + [None])] message = "Error: failed to stop '%s'. [%s]" % ( self.service_name, " ".join(res), ) self.error_msg.append(message) message = "Notice: '%s' is running. [PID:%s]" % ( self.service_name, ",".join(pids), ) retval = False else: message = "Error: '%s' not found." % (self.service_script, ) self.error_msg.append(message) return retval
def read_iptables_config(self): config = {} res = [] if is_readable(self.iptables_conf_file): res = ConfigFile(self.iptables_conf_file).read() ret = 0 if len(res) == 0: cmd = [] cmd.append(self._iptables_save) (ret,res) = execute_command(cmd) table_regex = re.compile(r"""^\*(?P<table>[a-z]+)""") policy_regex = re.compile(r"""^:(?P<chain>\S+) (?P<target>\S+)""") rule_regex = re.compile(r"""^\-A (?P<rule>\S+)""") end_regex = re.compile(r"""^COMMIT$""") if ret == 0 and len(res) > 0: for aline in res: aline = aline.rstrip() aline = aline.replace(RH_USERCHAIN,FIREWALL_USERCHAIN) m = end_regex.match(aline) if m is not None: for chain, policy in policies.iteritems(): rule = self._make_rule_arr(rules[chain]) info = {"policy": policies[chain], "rule": rule} table_info[chain] = info config[table] = table_info continue m = table_regex.match(aline) if m is not None: table = m.group("table") table_info = {} policies = {} rules = {} else: m = policy_regex.match(aline) if m is not None: chain = m.group("chain") target = m.group("target") policies[chain] = target rules[chain] = [] else: m = rule_regex.match(aline) if m is not None: rule_chain = m.group("rule") rules[rule_chain].append(aline) #pp = pprint.PrettyPrinter(indent=4) #pp.pprint(config) return config
def _do(self,action=None): from karesansui.lib.utils import execute_command retval = False res = [] if re.match("^(%s)$" % PARSER_IPTABLES_INITRD_ACTIONS, action): command_args = [PARSER_IPTABLES_INITRD,action] (ret,res) = execute_command(command_args) if ret == 0: retval = True return [retval,res]
def _do(self, action=None): from karesansui.lib.utils import execute_command retval = False res = [] if re.match("^(%s)$" % PARSER_IPTABLES_INITRD_ACTIONS, action): command_args = [PARSER_IPTABLES_INITRD, action] (ret, res) = execute_command(command_args) if ret == 0: retval = True return [retval, res]
def status(self): kmod_regex = re.compile(r"""^(ip_tables|iptable_filter|iptable_nat)[ \t]""") cmd = [] cmd.append(self._lsmod) (ret,res) = execute_command(cmd) if len(res) > 0: for aline in res: m = kmod_regex.match(aline) if m: return True return False
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) conn = KaresansuiVirtConnection(readonly=False) try: active_networks = conn.list_active_network() inactive_networks = conn.list_inactive_network() if not (opts.name in active_networks or opts.name in inactive_networks): raise KssCommandException('Could not find the specified network. - net=%s' % (opts.name)) self.up_progress(10) try: conn.stop_network(opts.name) except KaresansuiVirtException, e: if opt.force is not True: raise KssCommandException('Could not stop the specified network. - net=%s' % (opts.name)) self.up_progress(20) try: conn.start_network(opts.name) except KaresansuiVirtException, e: if opts.force is not True: raise KssCommandException('Could not start the specified network. - net=%s' % (opts.name)) # try to bring down existing bridge kvn = conn.search_kvn_networks(opts.name)[0] try: bridge_name = kvn.get_info()['bridge']['name'] except KeyError: pass ret, res = execute_command([NETWORK_IFCONFIG_COMMAND, bridge_name, 'down']) ret, res = execute_command([NETWORK_BRCTL_COMMAND, 'delbr', bridge_name]) # try again conn.start_network(opts.name)
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) network_restart_cmd = (NETWORK_COMMAND, "restart", ) (rc, res) = execute_command(network_restart_cmd) if rc != 0: raise KssCommandException('Failure restart network.') return True
def stop(self,force=False): """ <comment-ja> 制御対象サービスを停止する @param self: - @return boolean 成功:True 失敗:False </comment-ja> <comment-en> constructor of class @param self: The object pointer @return: none </comment-en> """ retval = False if force is False: pids = self.status() if force is False and len(pids) == 0: message = "Warning: '%s' already stopped." % (self.service_name,) self.error_msg.append(message) else: if os.path.exists(self.service_script) and is_executable(self.service_script): command = "%s stop" % (self.service_script,) command_args = command.split() #print command (ret,res) = execute_command(command_args) time.sleep(self.sleep_time) if force is False: pids = self.status() if force is True or len(pids) == 0: message = "Notice: succeeded to stop '%s'." % (self.service_name,) #print message retval = True else: pids = [str(p) for p, q in zip(pids, pids[1:] + [None])] message = "Error: failed to stop '%s'. [%s]" % (self.service_name," ".join(res),) self.error_msg.append(message) message = "Notice: '%s' is running. [PID:%s]" % (self.service_name,",".join(pids),) retval = False else: message = "Error: '%s' not found." % (self.service_script,) self.error_msg.append(message) return retval
def showKaresansuiVersion(self): print _("Using karesansui: %s %s.%s") %(__app__,__version__,__release__) (rc,res) = execute_command([COMMAND_LIGHTTPD,"-v"]) if rc == 0: p = re.compile("lighttpd-([0-9\.]+) .*") if p.search(res[0]): lighttpdVersion = p.sub("\\1",res[0]) print _("Using lighttpd: %s") %(lighttpdVersion) try: from pysilhouette import __app__ as pysilhouette_app from pysilhouette import __version__ as pysilhouette_ver from pysilhouette import __release__ as pysilhouette_rel print _("Using pysilhouette: %s %s.%s") %(pysilhouette_app,pysilhouette_ver,pysilhouette_rel) except: pass
def do_del(self,device,target): retval = True type = "-net" try: net = NetworkAddress(target) if net.netlen == 32: type = "-host" target = net.cidr except: pass command_args = [PARSER_COMMAND_ROUTE, "del", type, target, "dev", device] (ret,res) = execute_command(command_args) if ret != 0: retval = False return retval
def get_collectd_version(): retval = False from karesansui.lib.const import VENDOR_SBIN_DIR from karesansui.lib.utils import execute_command collectd_command = "%s/collectd" % VENDOR_SBIN_DIR command_args = [collectd_command,"-h"] (rc,res) = execute_command(command_args) for _line in res: if _line[0:9] == "collectd ": retval = _line.split()[1] if retval[-1:] == ",": retval = retval[0:-1] break return retval
def showKaresansuiVersion(self): print _("Using karesansui: %s %s.%s") % (__app__, __version__, __release__) (rc, res) = execute_command([COMMAND_LIGHTTPD, "-v"]) if rc == 0: p = re.compile("lighttpd-([0-9\.]+) .*") if p.search(res[0]): lighttpdVersion = p.sub("\\1", res[0]) print _("Using lighttpd: %s") % (lighttpdVersion) try: from pysilhouette import __app__ as pysilhouette_app from pysilhouette import __version__ as pysilhouette_ver from pysilhouette import __release__ as pysilhouette_rel print _("Using pysilhouette: %s %s.%s") % ( pysilhouette_app, pysilhouette_ver, pysilhouette_rel) except: pass
def read_conf(self): retval = {} for _afile in self.source_file(): if _afile[0:4] == "cmd:": command_args = _afile[4:].split() (ret,res) = execute_command(command_args) else: res = ConfigFile(_afile).read() new_res = [] for _aline in res: _aline = _aline.rstrip('\r\n') if self._comment != "" and not _aline.rfind(self._comment) == -1: _aline = _aline[:_aline.rfind(self._comment)] if _aline != "": new_res.append(_aline) self.dop.set(self._module,[_afile],new_res) #self.dop.preprint_r(self._module) return self.dop.getconf(self._module)
def refreshSnapshot(self): from karesansui.lib.utils import execute_command inactives = self.kvc.list_inactive_guest() actives = self.kvc.list_active_guest() do_refresh = False for domname in inactives + actives: all_num = self.listNum(domain=domname,all=True) active_num = self.listNum(domain=domname,all=False) if all_num > 0 and active_num == 0: do_refresh = True # 差分があれば実行 if do_refresh is True: command = "/etc/init.d/libvirtd restart" command_args = command.split(" ") (rc,res) = execute_command(command_args) pass return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(1) uniq_id = time.strftime("%Y%m%d%H%M%S", time.localtime()) if opts.pre_command is not None: if opts.pre_command[0:4] == "b64:": command = base64_decode(opts.pre_command[4:]) else: command = opts.pre_command self.logger.info("execute command - %s" % command) (_ret,_res) = execute_command(command.split()) if _ret != 0: error_msg = "execute error - %s" % command self.logger.error(error_msg) #raise KssCommandOptException("ERROR: %s" % error_msg) dop = DictOp() modules = opts.module.split(":") files = opts.file.split(":") source_files = [] retval = True cnt = 0 for _mod in modules: _file = files[cnt] try: exec("from karesansui.lib.parser.%s import %sParser as Parser" % (_mod,_mod,)) self.up_progress(5) parser = Parser() # 辞書オペレータに追加 self.up_progress(5) if opts.php is True: conf_arr = php_array_to_python_dict(open(_file).read()) else: exec("conf_arr = %s" % open(_file).read()) dop.addconf(_mod,conf_arr) """ 必要ならここで配列操作 通常は、配列操作後の辞書が_fileに書き込まれているので必要ない dop.add (_mod,"foo","bar") dop.delete(_mod,"foo") """ # 設定ファイル一覧に作成(バックアップ用) self.up_progress(5) source_file = parser.source_file() for _afile in source_file: _bak_afile = "%s.%s" % (_afile,uniq_id) copy_file(_afile,_bak_afile) source_files = source_files + source_file # 辞書に戻す self.up_progress(5) conf_arr = dop.getconf(_mod) #dop.preprint_r(_mod) # 設定ファイルに書き込み self.up_progress(5) extra_args = {} extra_args["include"] = opts.include if opts.early_exit is True: retval = retval and parser.write_conf(conf_arr,extra_args=extra_args) else: retval = parser.write_conf(conf_arr,extra_args=extra_args) and retval if opts.delete is True: os.unlink(_file) finally: cnt = cnt + 1 if retval is False: for _afile in source_files: _bak_afile = "%s.%s" % (_afile,uniq_id) os.unlink(_afile) copy_file(_bak_afile,_afile) os.unlink(_bak_afile) raise KssCommandOptException("ERROR: write configure failure") for _afile in source_files: _bak_afile = "%s.%s" % (_afile,uniq_id) os.unlink(_bak_afile) if opts.post_command is not None: if opts.post_command[0:4] == "b64:": command = base64_decode(opts.post_command[4:]) else: command = opts.post_command self.logger.info("execute command - %s" % command) (_ret,_res) = execute_command(command.split()) if _ret != 0: error_msg = "execute error - %s" % command self.logger.error(error_msg) raise KssCommandOptException("ERROR: %s" % error_msg) self.up_progress(10) return True
def read_conf(modules, webobj=None, machine=None, extra_args={}): """<comment-ja> 設定ファイルパーサー(モジュール)により設定ファイルの内容を 辞書配列操作クラスに渡し、そのオブジェクトを返す @param modules: モジュールのリスト配列 @param webobj: @param machine: @type modules: list @rtype: object dict_op @return: 辞書配列操作オブジェクト </comment-ja> <comment-en> TODO: English Comment </comment-en> """ if type(modules) == str: modules = [modules] options = {"module" : ":".join(modules)} try: options['include'] = extra_args['include'] except: pass #cmd_name = u"Get Settings - %s" % ":".join(modules) cmd_name = u"Get Settings" if type(webobj) == types.InstanceType: from karesansui.db.model._2pysilhouette import Job, JobGroup, \ JOBGROUP_TYPE from karesansui.db.access._2pysilhouette import jg_findby1, jg_save,corp from karesansui.db.access._2pysilhouette import save_job_collaboration from karesansui.db.access.machine2jobgroup import new as m2j_new from pysilhouette.command import dict2command _cmd = dict2command( "%s/%s" % (karesansui.config['application.bin.dir'], CONFIGURE_COMMAND_READ), options) jobgroup = JobGroup(cmd_name, karesansui.sheconf['env.uniqkey']) jobgroup.jobs.append(Job('%s command' % cmd_name, 0, _cmd)) jobgroup.type = JOBGROUP_TYPE['PARALLEL'] _machine2jobgroup = m2j_new(machine=machine, jobgroup_id=-1, uniq_key=karesansui.sheconf['env.uniqkey'], created_user=webobj.me, modified_user=webobj.me, ) if corp(webobj.orm, webobj.pysilhouette.orm,_machine2jobgroup, jobgroup) is False: webobj.logger.debug("%s command failed. Return to timeout" % (cmd_name)) return False cmd_res = jobgroup.jobs[0].action_stdout else: from karesansui.lib.utils import execute_command opts_str = "" for x in options.keys(): if options[x] is None: opts_str += "--%s " % x else: opts_str += "--%s=%s " % (x, options[x]) _cmd = "%s/bin/%s %s" % (KARESANSUI_PREFIX, CONFIGURE_COMMAND_READ, opts_str.strip(),) command_args = _cmd.strip().split(" ") (rc,res) = execute_command(command_args) if rc != 0: return False cmd_res = "\n".join(res) dop = DictOp() try: exec(cmd_res) except Exception: return False for module in modules: try: exec("dop.addconf('%s',Config_Dict_%s)" % (module,module,)) except: pass return dop
def write_conf(dop, webobj=None, machine=None, modules=[], extra_args={}): """<comment-ja> @param dop: 辞書配列操作オブジェクト @param webobj: @param machine: @type dop: object dict_op @rtype: boolean @return: True or False </comment-ja> <comment-en> TODO: English Comment </comment-en> """ from karesansui.lib.file.configfile import ConfigFile if isinstance(dop,karesansui.lib.dict_op.DictOp) is False: return False if not os.path.exists(CONF_TMP_DIR): os.makedirs(CONF_TMP_DIR) r_chmod(CONF_TMP_DIR,0770) r_chown(CONF_TMP_DIR,KARESANSUI_USER) r_chgrp(CONF_TMP_DIR,KARESANSUI_GROUP) serial = time.strftime("%Y%m%d%H%M%S",time.localtime()) if len(modules) == 0: modules = dop.ModuleNames w_modules = [] w_files = [] for _module in modules: if _module in dop.ModuleNames: filename = "%s/%s.%s" % (CONF_TMP_DIR,_module,serial,) data = preprint_r(dop.getconf(_module),return_var=True) ConfigFile(filename).write(data+"\n") r_chmod(filename,0660) r_chown(filename,KARESANSUI_USER) r_chgrp(filename,KARESANSUI_GROUP) w_modules.append(_module) w_files.append(filename) if len(w_modules) == 0: return False options = { "module" : ":".join(w_modules), "input-file" : ":".join(w_files), } options["delete"] = None try: extra_args['pre-command'] options['pre-command'] = "b64:" + base64_encode(extra_args['pre-command']) except: pass try: extra_args['post-command'] options['post-command'] = "b64:" + base64_encode(extra_args['post-command']) except: pass try: options['include'] = extra_args['include'] except: pass #cmd_name = u"Write Settings - %s" % ":".join(w_modules) cmd_name = u"Write Settings" if type(webobj) == types.InstanceType: from karesansui.db.model._2pysilhouette import Job, JobGroup, \ JOBGROUP_TYPE from karesansui.db.access._2pysilhouette import jg_findby1, jg_save,corp from karesansui.db.access._2pysilhouette import save_job_collaboration from karesansui.db.access.machine2jobgroup import new as m2j_new from pysilhouette.command import dict2command _cmd = dict2command( "%s/%s" % (karesansui.config['application.bin.dir'], CONFIGURE_COMMAND_WRITE), options) _jobgroup = JobGroup(cmd_name, karesansui.sheconf['env.uniqkey']) _jobgroup.jobs.append(Job('%s command' % cmd_name, 0, _cmd)) _machine2jobgroup = m2j_new(machine=machine, jobgroup_id=-1, uniq_key=karesansui.sheconf['env.uniqkey'], created_user=webobj.me, modified_user=webobj.me, ) save_job_collaboration(webobj.orm, webobj.pysilhouette.orm, _machine2jobgroup, _jobgroup, ) """ _jobgroup.type = JOBGROUP_TYPE['PARALLEL'] if corp(webobj.orm, webobj.pysilhouette.orm,_machine2jobgroup, _jobgroup) is False: webobj.logger.debug("%s command failed. Return to timeout" % (cmd_name)) for filename in w_files: if os.path.exists(filename): os.unlink(filename) return False cmd_res = jobgroup.jobs[0].action_stdout """ else: from karesansui.lib.utils import execute_command opts_str = "" for x in options.keys(): if options[x] is None: opts_str += "--%s " % x else: opts_str += "--%s=%s " % (x, options[x]) _cmd = "%s/bin/%s %s" % (KARESANSUI_PREFIX, CONFIGURE_COMMAND_WRITE, opts_str.strip(),) command_args = _cmd.strip().split(" ") (rc,res) = execute_command(command_args) if rc != 0: for filename in w_files: if os.path.exists(filename): os.unlink(filename) return False cmd_res = "\n".join(res) """ for filename in w_files: if os.path.exists(filename): os.unlink(filename) """ return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) node_command_args = (ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_NODE ) (node_rc, node_res) = execute_command(node_command_args) if node_rc != 0: for node_line in node_res: if node_line.find(ISCSI_CMD_RES_NO_NODE) != -1: self.logger.info("iSCSI node not found") return True raise KssCommandException('Failed to get iSCSI node. message=%s' % (node_res)) self.up_progress(20) session_command_args = (ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_SESSION ) (session_rc, session_res) = execute_command(session_command_args) if session_rc != 0: raise KssCommandException('Failed to get iSCSI session. message=%s' % (session_res)) self.up_progress(20) for node_line in node_res: if not node_line: continue try: node = iscsi_parse_node(node_line) except: self.logger.warn('Failed to parse iSCSI node command response. message="%s"' % (node_line)) continue is_active = 0 for session_line in session_res: if not session_line: continue if session_line.find(ISCSI_CMD_RES_NO_ACTIVE_SESSION) != -1: break try: session = iscsi_parse_session(session_line) except: self.logger.warn('Failed to parse iSCSI session command response. message="%s"' % (session_line)) continue if iscsi_check_node_status(node, session): is_active = 1 break if iscsi_check_node_autostart(node): autostart = 0 else: autostart = 1 if opts.iqn is None: self.logger.info("%s %s %s" % (iscsi_print_format_node(node), is_active, autostart)) print >>sys.stdout, _("%s %s %s") % (iscsi_print_format_node(node), is_active, autostart) else: if opts.iqn == node['iqn']: auth = iscsi_get_auth_type(node) user = iscsi_get_auth_user(node) self.logger.info("%s %s %s %s %s" % (iscsi_print_format_node(node), is_active, autostart, auth, user)) print >>sys.stdout, _("%s %s %s %s %s") % (iscsi_print_format_node(node), is_active, autostart, auth, user) break return True
def stop(self): cmd = [] cmd.append(self._iptables_init) cmd.append('stop') (ret, res) = execute_command(cmd) return ret
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) original_parser = iscsidParser() new_parser = iscsidParser() dop = DictOp() dop.addconf("original", original_parser.read_conf()) dop.addconf("new", new_parser.read_conf()) self.up_progress(10) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_METHOD, opts.auth) if opts.auth == ISCSI_CONFIG_VALUE_AUTH_METHOD_CHAP: password = "" if opts.password is not None: password = opts.password elif opts.password_file is not None and is_readable( opts.password_file): try: fp = open(opts.password_file, "r") try: fcntl.lockf(fp.fileno(), fcntl.LOCK_SH) try: password = fp.readline().strip("\n") finally: fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) self.up_progress(10) finally: fp.close() except: raise KssCommandException('Failed to read file. - target host=%s password_file=%s' \ % (opts.host,opts.password_file)) try: os.remove(opts.password_file) except: raise KssCommandException('Failed to remove file. - target host=%s password_file=%s' \ % (opts.host,opts.password_file)) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_METHOD, opts.auth) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_USER, opts.user) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_PASSWORD, password) else: dop.comment("new", ISCSI_CONFIG_KEY_AUTH_USER) dop.comment("new", ISCSI_CONFIG_KEY_AUTH_PASSWORD) self.up_progress(10) if opts.autostart: dop.cdp_set("new", ISCSI_CONFIG_KEY_SATRTUP, ISCSI_CONFIG_VALUE_SATRTUP_ON) else: dop.cdp_set("new", ISCSI_CONFIG_KEY_SATRTUP, ISCSI_CONFIG_VALUE_SATRTUP_OFF) new_parser.write_conf(dop.getconf("new")) self.up_progress(10) discovery_command_args = (ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_DISCOVERY, ISCSI_CMD_OPTION_TYPE, ISCSI_CMD_OPTION_TYPE_SENDTARGETS, ISCSI_CMD_OPTION_PORTAL, opts.host) (discovery_rc, discovery_res) = execute_command(discovery_command_args) self.up_progress(10) original_parser.write_conf(dop.getconf("original")) self.up_progress(10) if discovery_rc != 0: raise KssCommandException( 'Failed to add iSCSI. - host=%s message=%s' % (opts.host, discovery_res)) if discovery_res == []: raise KssCommandException( 'Failed to add iSCSI. - host=%s message=No exist permit iSCSI disk for target.' % (opts.host)) for node_line in discovery_res: if not node_line: continue try: node = iscsi_parse_node(node_line) except: self.logger.warn( 'Failed to parse iSCSI discovery command response. message="%s"' % (node_line)) continue self.logger.info("%s" % (iscsi_print_format_node(node))) print >> sys.stdout, _("%s") % (iscsi_print_format_node(node)) return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) exist_bond_list = get_ifconfig_info("regex:^bond") if opts.dev not in exist_bond_list: raise KssCommandOptException('Target bonding device not found. target=%s' % opts.dev) self.up_progress(10) dop = DictOp() ifcfg_parser = ifcfgParser() dop.addconf("ifcfg", ifcfg_parser.read_conf()) if dop.getconf("ifcfg") == {}: raise KssCommandException('Failure read network config file.') if dop.get("ifcfg", opts.dev) is False: raise KssCommandException('Target device ifcfg file not found.') self.up_progress(10) restore_dev_list = [] for dev in dop.getconf("ifcfg").keys(): if dop.get("ifcfg", [dev, "MASTER"]) == opts.dev: restore_dev_list.append(dev) self.up_progress(10) if opts.succession is True: bond_bridge = dop.get("ifcfg", [opts.dev, "BRIDGE"]) bond_dev = opts.dev if bond_bridge: bond_dev = bond_bridge ipaddr = dop.get("ifcfg", [bond_dev, "IPADDR"]) netmask = dop.get("ifcfg", [bond_dev, "NETMASK"]) gateway = dop.get("ifcfg", [bond_dev, "GATEWAY"]) bonding_opts = dop.get("ifcfg", [opts.dev, "BONDING_OPTS"]) bonding_opts = bonding_opts.strip('"') primary_dev = None for combination in bonding_opts.split(" "): if re.match("primary", combination): (key,val) = combination.split("=") val = val.strip() primary_dev = val self.up_progress(10) for restore_dev in restore_dev_list: if move_file("%s/ifcfg-%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev), NETWORK_IFCFG_DIR) is False: raise KssCommandException('Failure restore ifcfg file.') if os.path.isfile("%s/ifcfg-p%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev)): if move_file("%s/ifcfg-p%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev), NETWORK_IFCFG_DIR) is False: raise KssCommandException('Failure restore ifcfg file.') self.up_progress(10) if opts.succession is True and primary_dev is not None: dop = DictOp() ifcfg_parser = ifcfgParser() dop.addconf("ifcfg", ifcfg_parser.read_conf()) if dop.getconf("ifcfg") == {}: raise KssCommandException('Failure read network config file.') if ipaddr: dop.set("ifcfg", [primary_dev, "IPADDR"], ipaddr) if netmask: dop.set("ifcfg", [primary_dev, "NETMASK"], netmask) if gateway: dop.set("ifcfg", [primary_dev, "GATEWAY"], gateway) if ifcfg_parser.write_conf(dop.getconf("ifcfg")) is False: raise KssCommandException('Failure write network config file.') self.up_progress(10) remove_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, opts.dev)) self.up_progress(10) dop = DictOp() modprobe_parser = modprobe_confParser() dop.addconf("modprobe_conf", modprobe_parser.read_conf()) if dop.getconf("modprobe_conf") == {}: raise KssCommandException('Failure read modprobe config file.') dop.unset("modprobe_conf", ["alias", opts.dev]) if modprobe_parser.write_conf(dop.getconf("modprobe_conf")) is False: raise KssCommandException('Failure write modprobe config file.') self.up_progress(10) # # Delete bridge device # bridge_list = get_bridge_info() bond_bridge = None for bridge in bridge_list: if opts.dev in bridge_list[bridge]: bond_bridge = bridge if bond_bridge: ifdown_cmd = (NETWORK_IFDOWN_COMMAND, bond_bridge, ) (ifdown_rc, ifdown_res) = execute_command(ifdown_cmd) if ifdown_rc != 0: raise KssCommandException('Failure stop interface. interface:%s' % (dev)) for brif in bridge_list[bond_bridge]: brctl_delif_cmd = (NETWORK_BRCTL_COMMAND, "delif", bond_bridge, brif, ) (brctl_rc, brctl_res) = execute_command(brctl_delif_cmd) if brctl_rc != 0: raise KssCommandException('Failure delete bridge port. bridge:%s port:%s' % (dev, brif)) brctl_delbr_cmd = (NETWORK_BRCTL_COMMAND, "delbr", bond_bridge, ) (brctl_rc, brctl_res) = execute_command(brctl_delbr_cmd) if brctl_rc != 0: raise KssCommandException('Failure delete bridge. bridge:%s' % (dev, brif)) remove_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, bond_bridge)) # # Unload bonding module # remove_bonding_cmd = (SYSTEM_COMMAND_REMOVE_MODULE, "bonding", ) (rmmod_rc, rmmod_res) = execute_command(remove_bonding_cmd) if rmmod_rc != 0: raise KssCommandException('Failure remove bonding module.') # # Restart network # network_restart_cmd = (NETWORK_COMMAND, "restart", ) (net_rc, net_res) = execute_command(network_restart_cmd) if net_rc != 0: raise KssCommandException('Failure restart network.') self.logger.info("Deleted bonding device. - bond=%s dev=%s" % (opts.dev, ','.join(restore_dev_list))) print >>sys.stdout, _("Deleted bonding device. - bond=%s dev=%s" % (opts.dev, ','.join(restore_dev_list))) return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) node_command_args = (ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_NODE) (node_rc, node_res) = execute_command(node_command_args) if node_rc != 0: for node_line in node_res: if node_line.lower().find(ISCSI_CMD_RES_NO_NODE) != -1: self.logger.info("iSCSI node not found") return True raise KssCommandException('Failed to get iSCSI node. message=%s' % (node_res)) self.up_progress(20) session_command_args = (ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_SESSION) (session_rc, session_res) = execute_command(session_command_args) if session_rc != 0: raise KssCommandException( 'Failed to get iSCSI session. message=%s' % (session_res)) self.up_progress(20) for node_line in node_res: if not node_line: continue try: node = iscsi_parse_node(node_line) except: self.logger.warn( 'Failed to parse iSCSI node command response. message="%s"' % (node_line)) continue is_active = 0 for session_line in session_res: if not session_line: continue if session_line.find(ISCSI_CMD_RES_NO_ACTIVE_SESSION) != -1: break try: session = iscsi_parse_session(session_line) except: self.logger.warn( 'Failed to parse iSCSI session command response. message="%s"' % (session_line)) continue if iscsi_check_node_status(node, session): is_active = 1 break if iscsi_check_node_autostart(node): autostart = 0 else: autostart = 1 if opts.iqn is None: self.logger.info( "%s %s %s" % (iscsi_print_format_node(node), is_active, autostart)) print >> sys.stdout, _("%s %s %s") % ( iscsi_print_format_node(node), is_active, autostart) else: if opts.iqn == node['iqn']: auth = iscsi_get_auth_type(node) user = iscsi_get_auth_user(node) self.logger.info("%s %s %s %s %s" % (iscsi_print_format_node(node), is_active, autostart, auth, user)) print >> sys.stdout, _("%s %s %s %s %s") % ( iscsi_print_format_node(node), is_active, autostart, auth, user) break return True
def onboot(self, flag=None, runlevel=None): """ <comment-ja> 制御対象サービスのマシン起動時の起動状態の有効/無効の切り替えを行う。 または、その状態を取得する。 @param self: - @param string flag 指定なし:状態を取得する True :起動時有効にする False :起動時無効にする @return boolean True :状態取得なら起動時有効、起動時切替なら成功 False:状態取得なら起動時有効、起動時切替なら成功 </comment-ja> <comment-en> constructor of class @param self: The object pointer @return: none </comment-en> """ retval = False if flag is not None and flag is not True and flag is not False: raise Exception("Invalid argument.") if os.path.exists(self.service_script) and is_executable( self.service_script): script_name = os.path.basename(self.service_script) old_lang = os.environ["LANG"] os.environ["LANG"] = "C" if flag is None: command = "%s --list %s" % ( self.command_chkconfig, script_name, ) command_args = command.split() (ret, res) = execute_command(command_args) if runlevel is None: runlevel = self.runlevel try: m = re.search("[ \t]+%s:on[ \t]+" % runlevel, res[0]) if m: retval = True except: pass else: if flag is True: on_or_off = "on" else: on_or_off = "off" if runlevel is None: command = "%s %s %s" % (self.command_chkconfig, script_name, on_or_off) else: command = "%s --level %s %s %s" % (self.command_chkconfig, runlevel, script_name, on_or_off) command_args = command.split() (ret, res) = execute_command(command_args) if ret == 0: retval = True os.environ["LANG"] = old_lang else: message = "Error: '%s' not found." % (self.service_script, ) self.error_msg.append(message) return retval
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) already_exist = False session_command_args = (ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_SESSION ) (session_rc, session_res) = execute_command(session_command_args) if session_rc != 0: raise KssCommandException('Failed to get iSCSI session. message=%s' % (session_res)) for session_line in session_res: if not session_line: continue if session_line.find(ISCSI_CMD_RES_NO_ACTIVE_SESSION) != -1: break try: session = iscsi_parse_session(session_line) except: self.logger.warn('Failed to parse iSCSI session command response. message="%s"' % (session_line)) continue if session['iqn'] == opts.iqn: if opts.host: if opts.host != session['hostname']: continue already_exist = True break if already_exist: self.logger.info("[target: %s]: already exists" % (opts.iqn)) print >>sys.stdout, _("[target: %s]: already exists") % (opts.iqn) else: login_command_args = [ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_NODE, ISCSI_CMD_OPTION_TARGETNAME, opts.iqn, ] if opts.host: login_command_args.append(ISCSI_CMD_OPTION_PORTAL) login_command_args.append(opts.host) login_command_args.append(ISCSI_CMD_OPTION_LOGIN) (login_rc,login_res) = execute_command(login_command_args) self.up_progress(50) if login_rc != 0: raise KssCommandException('Failed to login to iSCSI. - host=%s iqn=%s message=%s' % (opts.host, opts.iqn, login_res)) for line in login_res: if not line: continue self.logger.info("%s" % (line)) print >>sys.stdout, _("%s") % (line) return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) dev_list = comma_split(opts.dev) if len(dev_list) < 2: # TRANSLATORS: # bondingするためのdeviceが少ないです raise KssCommandOptException('ERROR: Small device for bonding. - dev=%s' % (opts.dev)) interface_list = get_ifconfig_info() for dev in dev_list: if dev not in interface_list: raise KssCommandOptException('ERROR: Bonding target device not found. - dev=%s' % (dev)) if opts.primary not in dev_list: raise KssCommandOptException('ERROR: Primary device not found in bonding device. - primary=%s dev=%s' % (opts.primary, opts.dev)) exist_bond_max_num = -1 exist_bond_list = get_ifconfig_info("regex:^bond") for bond_name in exist_bond_list.keys(): try: num = int(bond_name.replace("bond","")) except ValueError: continue if exist_bond_max_num < num: exist_bond_max_num = num self.up_progress(10) physical_bond_name = "bond%s" % (exist_bond_max_num + 1) bridge_bond_name = "bondbr%s" % (exist_bond_max_num + 1) bond_options = '"mode=%s primary=%s miimon=%s"' % (opts.mode, opts.primary, BONDING_CONFIG_MII_DEFAULT) self.up_progress(10) dop = DictOp() ifcfg_parser = ifcfgParser() modprobe_parser = modprobe_confParser() dop.addconf("ifcfg", ifcfg_parser.read_conf()) if dop.getconf("ifcfg") == {}: raise KssCommandException('Failure read network config file.') dop.addconf("modprobe_conf", modprobe_parser.read_conf()) if dop.getconf("modprobe_conf") == {}: raise KssCommandException('Failure read modprobe config file.') self.up_progress(10) eth_conf_copykey = ["HWADDR", "BOOTPROTO", "ONBOOT", "USERCTL", ] bond_conf_nocopykey = ["TYPE", "HWADDR", "MACADDR", "ETHTOOL_OPTS", "ESSID", "CHANNEL", ] self.up_progress(10) for dev in dev_list: conf = dop.get("ifcfg", dev) if dev == opts.primary: primary_conf = copy.deepcopy(conf) dop.unset("ifcfg", dev) dop.set("ifcfg", [dev, "DEVICE"], conf["DEVICE"]["value"]) for key in eth_conf_copykey: if key in conf: dop.set("ifcfg", [dev, key], conf[key]["value"]) dop.set("ifcfg", [dev, "MASTER"], physical_bond_name) dop.set("ifcfg", [dev, "SLAVE"], "yes") dop.set("ifcfg", [dev, "BOOTPROTO"], "none") if dop.get("ifcfg", "p%s" % (dev)): hwaddr = dop.get("ifcfg", ["p%s" % (dev), "HWADDR"]) if hwaddr: dop.set("ifcfg", [dev, "HWADDR"], hwaddr) dop.unset("ifcfg", "p%s" % (dev)) for key in bond_conf_nocopykey: if key in primary_conf: del primary_conf[key] dop.set("ifcfg", bridge_bond_name, primary_conf) dop.set("ifcfg", [bridge_bond_name, "DEVICE"], bridge_bond_name) dop.set("ifcfg", [bridge_bond_name, "TYPE"], "Bridge") dop.set("ifcfg", [physical_bond_name, "DEVICE"], physical_bond_name) dop.set("ifcfg", [physical_bond_name, "BRIDGE"], bridge_bond_name) dop.set("ifcfg", [physical_bond_name, "BOOTPROTO"], "none") dop.set("ifcfg", [physical_bond_name, "ONBOOT"], dop.get("ifcfg", [bridge_bond_name, "ONBOOT"])) dop.set("ifcfg", [physical_bond_name, "BONDING_OPTS"], bond_options) self.up_progress(10) dop.set("modprobe_conf", ["alias", physical_bond_name], "bonding") for dev in dev_list: if os.path.isfile("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev)): copy_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev), VENDOR_DATA_BONDING_EVACUATION_DIR) if os.path.isfile("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev)): move_file("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev), VENDOR_DATA_BONDING_EVACUATION_DIR) if ifcfg_parser.write_conf(dop.getconf("ifcfg")) is False: raise KssCommandException('Failure write network config file.') if modprobe_parser.write_conf(dop.getconf("modprobe_conf")) is False: raise KssCommandException('Failure write modprobe config file.') self.up_progress(10) # # Delete bridge device # bridge_list = get_bridge_info() for dev in dev_list: if dev in bridge_list: ifdown_cmd = (NETWORK_IFDOWN_COMMAND, dev, ) (ifdown_rc, ifdown_res) = execute_command(ifdown_cmd) if ifdown_rc != 0: raise KssCommandException('Failure stop interface. interface:%s' % (dev)) for brif in bridge_list[dev]: brctl_delif_cmd = (NETWORK_BRCTL_COMMAND, "delif", dev, brif, ) (brctl_rc, brctl_res) = execute_command(brctl_delif_cmd) if brctl_rc != 0: raise KssCommandException('Failure delete bridge port. bridge:%s port:%s' % (dev, brif)) brctl_delbr_cmd = (NETWORK_BRCTL_COMMAND, "delbr", dev, ) (brctl_rc, brctl_res) = execute_command(brctl_delbr_cmd) if brctl_rc != 0: raise KssCommandException('Failure delete bridge. bridge:%s' % (dev, brif)) self.up_progress(10) # # Restart network # network_restart_cmd = (NETWORK_COMMAND, "restart", ) (net_rc, net_res) = execute_command(network_restart_cmd) if net_rc != 0: raise KssCommandException('Failure restart network.') self.logger.info("Created bonding device. - dev=%s bond=%s" % (opts.dev, bridge_bond_name)) print >>sys.stdout, _("Created bonding device. - dev=%s bond=%s" % (opts.dev, bridge_bond_name)) return True
source_file = parser.source_file() print ">" + _("Detecting configuration files") print "\n".join(source_file) print "<" + _("Detecting configuration files") output_file = "%s/%s_dict.py" % (save_path,_mod,) if use_read_conf is True: command_args = [] command_args.append(command_read_conf) command_args.append("--module") command_args.append(_mod) command_args.append("--file") command_args.append(output_file) print ">" + _("Reading configuration files") print ">>" + _("Execute") + "=>" + " ".join(command_args) (ret, res) = execute_command(command_args) if len(res) > 0: print ">>" + _("Execute Result") + "=>\n" + "\n".join(res) print "<" + _("Reading configuration files") else: print ">" + _("Reading configuration files") dop.addconf(_mod,parser.read_conf()) print "<" + _("Reading configuration files") print ">" + _("Writing module dict files") conf = dop.getconf(_mod) ConfigFile(output_file).write(str(conf)) print "<" + _("Writing module dict files") if os.path.exists(output_file):
def restart(self): cmd = [] cmd.append(self._iptables_init) cmd.append('restart') (ret, res) = execute_command(cmd) return ret
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) try: tmp_dir_name = generate_phrase(12,'abcdefghijklmnopqrstuvwxyz') tmp_dir_path = "%s/%s" % (KARESANSUI_TMP_DIR, tmp_dir_name) os.mkdir(tmp_dir_path) except: raise KssCommandException('Failed to make tmpdir. path=%s' % (tmp_dir_path)) try: self.up_progress(10) mount_command_args = (MOUNT_CMD, opts.dev, tmp_dir_path, ) umount_command_args = (UMOUNT_CMD, tmp_dir_path, ) is_mountable = False try: (mount_cmd_rc, mount_cmd_res) = execute_command(mount_command_args) if mount_cmd_rc == 0: is_mountable = True else: self.logger.debug('Failed to mount. dev=%s' % (opts.dev)) finally: (umount_cmd_rc, umount_cmd_res) = execute_command(umount_command_args) self.up_progress(30) if is_mountable is False and opts.format is True: first_command_args = YES_CMD second_command_args = (FORMAT_CMD, "-t", opts.type, opts.dev, ) format_command_args = (first_command_args, second_command_args, ) (format_cmd_rc, format_cmd_res) = pipe_execute_command(format_command_args) if format_cmd_rc != 0: raise KssCommandException('Failed to format. dev=%s type=%s res=%s' % (opts.dev, opts.type, format_cmd_res)) try: (mount_cmd_rc, mount_cmd_res) = execute_command(mount_command_args) if mount_cmd_rc == 0: is_mountable = True else: self.logger.debug('Failed to mount. dev=%s' % (opts.dev)) finally: (umount_cmd_rc, umount_cmd_res) = execute_command(umount_command_args) self.up_progress(40) finally: try: os.rmdir(tmp_dir_path) except: raise KssCommandException('Failed to delete tmpdir. path=%s' % (tmp_dir_path)) if is_mountable is True: self.logger.info('Device "%s" is mountable.' % (opts.dev)) print >>sys.stdout, _('Device "%s" is mountable.' % (opts.dev)) else: self.logger.info('Device "%s" is not mountable.' % (opts.dev)) print >>sys.stdout, _('Device "%s" is not mountable.' % (opts.dev)) return is_mountable
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) exist_bond_list = get_ifconfig_info("regex:^bond") if opts.dev not in exist_bond_list: raise KssCommandOptException( 'Target bonding device not found. target=%s' % opts.dev) self.up_progress(10) dop = DictOp() ifcfg_parser = ifcfgParser() dop.addconf("ifcfg", ifcfg_parser.read_conf()) if dop.getconf("ifcfg") == {}: raise KssCommandException('Failure read network config file.') if dop.get("ifcfg", opts.dev) is False: raise KssCommandException('Target device ifcfg file not found.') self.up_progress(10) restore_dev_list = [] for dev in dop.getconf("ifcfg").keys(): if dop.get("ifcfg", [dev, "MASTER"]) == opts.dev: restore_dev_list.append(dev) self.up_progress(10) if opts.succession is True: bond_bridge = dop.get("ifcfg", [opts.dev, "BRIDGE"]) bond_dev = opts.dev if bond_bridge: bond_dev = bond_bridge ipaddr = dop.get("ifcfg", [bond_dev, "IPADDR"]) netmask = dop.get("ifcfg", [bond_dev, "NETMASK"]) gateway = dop.get("ifcfg", [bond_dev, "GATEWAY"]) bonding_opts = dop.get("ifcfg", [opts.dev, "BONDING_OPTS"]) bonding_opts = bonding_opts.strip('"') primary_dev = None for combination in bonding_opts.split(" "): if re.match("primary", combination): (key, val) = combination.split("=") val = val.strip() primary_dev = val self.up_progress(10) for restore_dev in restore_dev_list: if move_file( "%s/ifcfg-%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev), NETWORK_IFCFG_DIR) is False: raise KssCommandException('Failure restore ifcfg file.') if os.path.isfile( "%s/ifcfg-p%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev)): if move_file( "%s/ifcfg-p%s" % (VENDOR_DATA_BONDING_EVACUATION_DIR, restore_dev), NETWORK_IFCFG_DIR) is False: raise KssCommandException('Failure restore ifcfg file.') self.up_progress(10) if opts.succession is True and primary_dev is not None: dop = DictOp() ifcfg_parser = ifcfgParser() dop.addconf("ifcfg", ifcfg_parser.read_conf()) if dop.getconf("ifcfg") == {}: raise KssCommandException('Failure read network config file.') if ipaddr: dop.set("ifcfg", [primary_dev, "IPADDR"], ipaddr) if netmask: dop.set("ifcfg", [primary_dev, "NETMASK"], netmask) if gateway: dop.set("ifcfg", [primary_dev, "GATEWAY"], gateway) if ifcfg_parser.write_conf(dop.getconf("ifcfg")) is False: raise KssCommandException('Failure write network config file.') self.up_progress(10) remove_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, opts.dev)) self.up_progress(10) dop = DictOp() modprobe_parser = modprobe_confParser() dop.addconf("modprobe_conf", modprobe_parser.read_conf()) if dop.getconf("modprobe_conf") == {}: raise KssCommandException('Failure read modprobe config file.') dop.unset("modprobe_conf", ["alias", opts.dev]) if modprobe_parser.write_conf(dop.getconf("modprobe_conf")) is False: raise KssCommandException('Failure write modprobe config file.') self.up_progress(10) # # Delete bridge device # bridge_list = get_bridge_info() bond_bridge = None for bridge in bridge_list: if opts.dev in bridge_list[bridge]: bond_bridge = bridge if bond_bridge: ifdown_cmd = ( NETWORK_IFDOWN_COMMAND, bond_bridge, ) (ifdown_rc, ifdown_res) = execute_command(ifdown_cmd) if ifdown_rc != 0: raise KssCommandException( 'Failure stop interface. interface:%s' % (dev)) for brif in bridge_list[bond_bridge]: brctl_delif_cmd = ( NETWORK_BRCTL_COMMAND, "delif", bond_bridge, brif, ) (brctl_rc, brctl_res) = execute_command(brctl_delif_cmd) if brctl_rc != 0: raise KssCommandException( 'Failure delete bridge port. bridge:%s port:%s' % (dev, brif)) brctl_delbr_cmd = ( NETWORK_BRCTL_COMMAND, "delbr", bond_bridge, ) (brctl_rc, brctl_res) = execute_command(brctl_delbr_cmd) if brctl_rc != 0: raise KssCommandException('Failure delete bridge. bridge:%s' % (dev, brif)) remove_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, bond_bridge)) # # Unload bonding module # remove_bonding_cmd = ( SYSTEM_COMMAND_REMOVE_MODULE, "bonding", ) (rmmod_rc, rmmod_res) = execute_command(remove_bonding_cmd) if rmmod_rc != 0: raise KssCommandException('Failure remove bonding module.') # # Restart network # network_restart_cmd = ( NETWORK_COMMAND, "restart", ) (net_rc, net_res) = execute_command(network_restart_cmd) if net_rc != 0: raise KssCommandException('Failure restart network.') self.logger.info("Deleted bonding device. - bond=%s dev=%s" % (opts.dev, ','.join(restore_dev_list))) print >> sys.stdout, _("Deleted bonding device. - bond=%s dev=%s" % (opts.dev, ','.join(restore_dev_list))) return True
def stop(self): cmd = [] cmd.append(self._iptables_init) cmd.append('stop') (ret,res) = execute_command(cmd) return ret
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) original_parser = iscsidParser() new_parser = iscsidParser() dop = DictOp() dop.addconf("original", original_parser.read_conf()) dop.addconf("new", new_parser.read_conf()) self.up_progress(10) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_METHOD, opts.auth) if opts.auth == ISCSI_CONFIG_VALUE_AUTH_METHOD_CHAP: password = "" if opts.password is not None: password = opts.password elif opts.password_file is not None and is_readable(opts.password_file): try: fp = open(opts.password_file, "r") try: fcntl.lockf(fp.fileno(), fcntl.LOCK_SH) try: password = fp.readline().strip("\n") finally: fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) self.up_progress(10) finally: fp.close() except: raise KssCommandException('Failed to read file. - target host=%s password_file=%s' \ % (opts.host,opts.password_file)) try: os.remove(opts.password_file) except: raise KssCommandException('Failed to remove file. - target host=%s password_file=%s' \ % (opts.host,opts.password_file)) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_METHOD, opts.auth) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_USER, opts.user) dop.cdp_set("new", ISCSI_CONFIG_KEY_AUTH_PASSWORD, password) else: dop.comment("new", ISCSI_CONFIG_KEY_AUTH_USER) dop.comment("new", ISCSI_CONFIG_KEY_AUTH_PASSWORD) self.up_progress(10) if opts.autostart: dop.cdp_set("new", ISCSI_CONFIG_KEY_SATRTUP, ISCSI_CONFIG_VALUE_SATRTUP_ON) else: dop.cdp_set("new", ISCSI_CONFIG_KEY_SATRTUP, ISCSI_CONFIG_VALUE_SATRTUP_OFF) new_parser.write_conf(dop.getconf("new")) self.up_progress(10) discovery_command_args = (ISCSI_CMD, ISCSI_CMD_OPTION_MODE, ISCSI_CMD_OPTION_MODE_DISCOVERY, ISCSI_CMD_OPTION_TYPE, ISCSI_CMD_OPTION_TYPE_SENDTARGETS, ISCSI_CMD_OPTION_PORTAL, opts.host ) (discovery_rc,discovery_res) = execute_command(discovery_command_args) self.up_progress(10) original_parser.write_conf(dop.getconf("original")) self.up_progress(10) if discovery_rc != 0: raise KssCommandException('Failed to add iSCSI. - host=%s message=%s' % (opts.host, discovery_res)) if discovery_res == []: raise KssCommandException('Failed to add iSCSI. - host=%s message=No exist permit iSCSI disk for target.' % (opts.host)) for node_line in discovery_res: if not node_line: continue try: node = iscsi_parse_node(node_line) except: self.logger.warn('Failed to parse iSCSI discovery command response. message="%s"' % (node_line)) continue self.logger.info("%s" % (iscsi_print_format_node(node))) print >>sys.stdout, _("%s") % (iscsi_print_format_node(node)) return True
def process(self): (opts, args) = getopts() chkopts(opts) self.up_progress(10) dev_list = comma_split(opts.dev) if len(dev_list) < 2: # TRANSLATORS: # bondingするためのdeviceが少ないです raise KssCommandOptException( 'ERROR: Small device for bonding. - dev=%s' % (opts.dev)) interface_list = get_ifconfig_info() for dev in dev_list: if dev not in interface_list: raise KssCommandOptException( 'ERROR: Bonding target device not found. - dev=%s' % (dev)) if opts.primary not in dev_list: raise KssCommandOptException( 'ERROR: Primary device not found in bonding device. - primary=%s dev=%s' % (opts.primary, opts.dev)) exist_bond_max_num = -1 exist_bond_list = get_ifconfig_info("regex:^bond") for bond_name in exist_bond_list.keys(): try: num = int(bond_name.replace("bond", "")) except ValueError: continue if exist_bond_max_num < num: exist_bond_max_num = num self.up_progress(10) physical_bond_name = "bond%s" % (exist_bond_max_num + 1) bridge_bond_name = "bondbr%s" % (exist_bond_max_num + 1) bond_options = '"mode=%s primary=%s miimon=%s"' % ( opts.mode, opts.primary, BONDING_CONFIG_MII_DEFAULT) self.up_progress(10) dop = DictOp() ifcfg_parser = ifcfgParser() modprobe_parser = modprobe_confParser() dop.addconf("ifcfg", ifcfg_parser.read_conf()) if dop.getconf("ifcfg") == {}: raise KssCommandException('Failure read network config file.') dop.addconf("modprobe_conf", modprobe_parser.read_conf()) if dop.getconf("modprobe_conf") == {}: raise KssCommandException('Failure read modprobe config file.') self.up_progress(10) eth_conf_copykey = [ "HWADDR", "BOOTPROTO", "ONBOOT", "USERCTL", ] bond_conf_nocopykey = [ "TYPE", "HWADDR", "MACADDR", "ETHTOOL_OPTS", "ESSID", "CHANNEL", ] self.up_progress(10) for dev in dev_list: conf = dop.get("ifcfg", dev) if dev == opts.primary: primary_conf = copy.deepcopy(conf) dop.unset("ifcfg", dev) dop.set("ifcfg", [dev, "DEVICE"], conf["DEVICE"]["value"]) for key in eth_conf_copykey: if key in conf: dop.set("ifcfg", [dev, key], conf[key]["value"]) dop.set("ifcfg", [dev, "MASTER"], physical_bond_name) dop.set("ifcfg", [dev, "SLAVE"], "yes") dop.set("ifcfg", [dev, "BOOTPROTO"], "none") if dop.get("ifcfg", "p%s" % (dev)): hwaddr = dop.get("ifcfg", ["p%s" % (dev), "HWADDR"]) if hwaddr: dop.set("ifcfg", [dev, "HWADDR"], hwaddr) dop.unset("ifcfg", "p%s" % (dev)) for key in bond_conf_nocopykey: if key in primary_conf: del primary_conf[key] dop.set("ifcfg", bridge_bond_name, primary_conf) dop.set("ifcfg", [bridge_bond_name, "DEVICE"], bridge_bond_name) dop.set("ifcfg", [bridge_bond_name, "TYPE"], "Bridge") dop.set("ifcfg", [physical_bond_name, "DEVICE"], physical_bond_name) dop.set("ifcfg", [physical_bond_name, "BRIDGE"], bridge_bond_name) dop.set("ifcfg", [physical_bond_name, "BOOTPROTO"], "none") dop.set("ifcfg", [physical_bond_name, "ONBOOT"], dop.get("ifcfg", [bridge_bond_name, "ONBOOT"])) dop.set("ifcfg", [physical_bond_name, "BONDING_OPTS"], bond_options) self.up_progress(10) dop.set("modprobe_conf", ["alias", physical_bond_name], "bonding") for dev in dev_list: if os.path.isfile("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev)): copy_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev), VENDOR_DATA_BONDING_EVACUATION_DIR) if os.path.isfile("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev)): move_file("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev), VENDOR_DATA_BONDING_EVACUATION_DIR) if ifcfg_parser.write_conf(dop.getconf("ifcfg")) is False: raise KssCommandException('Failure write network config file.') if modprobe_parser.write_conf(dop.getconf("modprobe_conf")) is False: raise KssCommandException('Failure write modprobe config file.') self.up_progress(10) # # Delete bridge device # bridge_list = get_bridge_info() for dev in dev_list: if dev in bridge_list: ifdown_cmd = ( NETWORK_IFDOWN_COMMAND, dev, ) (ifdown_rc, ifdown_res) = execute_command(ifdown_cmd) if ifdown_rc != 0: raise KssCommandException( 'Failure stop interface. interface:%s' % (dev)) for brif in bridge_list[dev]: brctl_delif_cmd = ( NETWORK_BRCTL_COMMAND, "delif", dev, brif, ) (brctl_rc, brctl_res) = execute_command(brctl_delif_cmd) if brctl_rc != 0: raise KssCommandException( 'Failure delete bridge port. bridge:%s port:%s' % (dev, brif)) brctl_delbr_cmd = ( NETWORK_BRCTL_COMMAND, "delbr", dev, ) (brctl_rc, brctl_res) = execute_command(brctl_delbr_cmd) if brctl_rc != 0: raise KssCommandException( 'Failure delete bridge. bridge:%s' % (dev, brif)) self.up_progress(10) # # Restart network # network_restart_cmd = ( NETWORK_COMMAND, "restart", ) (net_rc, net_res) = execute_command(network_restart_cmd) if net_rc != 0: raise KssCommandException('Failure restart network.') self.logger.info("Created bonding device. - dev=%s bond=%s" % (opts.dev, bridge_bond_name)) print >> sys.stdout, _("Created bonding device. - dev=%s bond=%s" % (opts.dev, bridge_bond_name)) return True
def restart(self): cmd = [] cmd.append(self._iptables_init) cmd.append('restart') (ret,res) = execute_command(cmd) return ret
def exec_script(script="",user="******",msg="",watch_name="",logfile="/dev/null"): retval = False func_name = sys._getframe(0).f_code.co_name append_line(logfile,"[%s] Entering function '%s'." % (func_name,func_name,)) # スクリプトの一時保存ディレクトリを作成 SCRIPT_TMP_DIR = "%s/tmp/.script" % (KARESANSUI_DATA_DIR,) if not os.path.exists(SCRIPT_TMP_DIR): os.makedirs(SCRIPT_TMP_DIR) r_chmod(SCRIPT_TMP_DIR,0770) r_chown(SCRIPT_TMP_DIR,KARESANSUI_USER) r_chgrp(SCRIPT_TMP_DIR,KARESANSUI_GROUP) append_line(logfile,"[%s] Create directory '%s'." % (func_name,SCRIPT_TMP_DIR,)) try: user_id = int(user) except: user_id = pwd.getpwnam(user)[2] # スクリプトファイルの生成 fname = None try: fd, fname = tempfile.mkstemp(suffix="",prefix="script_",dir=SCRIPT_TMP_DIR) append_line(logfile,"[%s] Create script '%s'." % (func_name,fname,)) fp = os.fdopen(fd,"w") fcntl.lockf(fp.fileno(), fcntl.LOCK_EX) script = re.sub("%{watch_name}",watch_name.encode('utf_8'),script) script = re.sub("%{msg}" ,msg.encode('utf_8') ,script) fp.write(script) fcntl.lockf(fp.fileno(), fcntl.LOCK_UN) fp.close() os.chmod(fname,0700) os.chown(fname,user_id,-1) except: append_line(logfile,"[%s] Error: failed to create script." % (func_name,)) if fname is not None and os.path.exists(fname): os.unlink(fname) if fname is not None and os.path.exists(fname): # マジッククッキーを調べる magic_cookie = open(fname).readline().rstrip() if magic_cookie[-8:] == "bin/perl": interpreter = "perl" elif magic_cookie[-10:] == "bin/python" or \ magic_cookie[-10:] == "env python": interpreter = "python" elif magic_cookie[-7:] == "bin/php": interpreter = "php" elif magic_cookie[-8:] == "bin/ruby": interpreter = "ruby" elif magic_cookie[-8:] == "bin/tcsh": interpreter = "tcsh" elif magic_cookie[-7:] == "bin/csh": interpreter = "csh" else: interpreter = "sh" # コマンド文字列の作成 if os.getuid() != user_id: command_args = ["su","-s", "/bin/bash", user, fname] else: command_args = [interpreter,fname] # コマンドの実行 append_line(logfile,"[%s] Execute command '%s'." % (func_name," ".join(command_args),)) (rc,res) = execute_command(command_args) new_res = [] for _aline in res: append_line(logfile,"[%s] output> %s" % (func_name,_aline,)) _aline = re.sub("^%s:[ \t]+" % fname, "", _aline) new_res.append(_aline) pass append_line(logfile,"[%s] command return value = %d" % (func_name,rc,)) os.unlink(fname) retval = [rc,new_res] else: append_line(logfile,"[%s] Error: cannot create script file." % (func_name,)) append_line(logfile,"[%s] Leaving function '%s'." % (func_name,func_name,)) return retval
def iptables_lint(filepath, webobj=None, machine=None, delete=False): from karesansui.lib.const import IPTABLES_COMMAND_CONTROL options = {"config" : filepath, "lint" : None} cmd_name = u"Check iptables settings - %s" % filepath if type(webobj) == types.InstanceType: from karesansui.db.model._2pysilhouette import Job, JobGroup, \ JOBGROUP_TYPE from karesansui.db.access._2pysilhouette import jg_findby1, jg_save,corp from karesansui.db.access._2pysilhouette import save_job_collaboration from karesansui.db.access.machine2jobgroup import new as m2j_new from pysilhouette.command import dict2command _cmd = dict2command( "%s/%s" % (karesansui.config['application.bin.dir'], IPTABLES_COMMAND_CONTROL), options) jobgroup = JobGroup(cmd_name, karesansui.sheconf['env.uniqkey']) jobgroup.jobs.append(Job('%s command' % cmd_name, 0, _cmd)) jobgroup.type = JOBGROUP_TYPE['PARALLEL'] _machine2jobgroup = m2j_new(machine=machine, jobgroup_id=-1, uniq_key=karesansui.sheconf['env.uniqkey'], created_user=webobj.me, modified_user=webobj.me, ) if corp(webobj.orm, webobj.pysilhouette.orm,_machine2jobgroup, jobgroup) is False: webobj.logger.debug("%s command failed. Return to timeout" % (cmd_name)) if delete is True and os.path.exists(filepath): os.unlink(filepath) return False cmd_res = jobgroup.jobs[0].action_stdout else: from karesansui.lib.const import KARESANSUI_PREFIX from karesansui.lib.utils import execute_command opts_str = "" for x in options.keys(): if options[x] is None: opts_str += "--%s " % x else: opts_str += "--%s=%s " % (x, options[x]) _cmd = "%s/bin/%s %s" % (KARESANSUI_PREFIX, IPTABLES_COMMAND_CONTROL, opts_str.strip(),) command_args = _cmd.strip().split(" ") (rc,res) = execute_command(command_args) if rc != 0: if delete is True and os.path.exists(filepath): os.unlink(filepath) return False cmd_res = "\n".join(res) if delete is True and os.path.exists(filepath): os.unlink(filepath) return cmd_res