当前位置: 首页>>代码示例>>Python>>正文


Python DictOp.set方法代码示例

本文整理汇总了Python中karesansui.lib.dict_op.DictOp.set方法的典型用法代码示例。如果您正苦于以下问题:Python DictOp.set方法的具体用法?Python DictOp.set怎么用?Python DictOp.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在karesansui.lib.dict_op.DictOp的用法示例。


在下文中一共展示了DictOp.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _new_lines

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
    def _new_lines(self,search_key,new_key):

        try:
            attrs = self.dop.get(self._module,search_key,with_attr=True)
            action    = attrs['action']
            iscomment = attrs['comment']
            val       = attrs['value']
        except:
            action    = self.dop.action(self._module,search_key)
            iscomment = self.dop.iscomment(self._module,search_key)
            val       = self.dop.get(self._module,search_key)
            pass

        #print val
        dop = DictOp()
        dop.addconf('__',{})
        if action == "delete":
            dop.add('__',new_key,val)
            dop.delete('__',new_key)
        elif action == "set":
            dop.set('__',new_key,val)
        else:
            dop.add('__',new_key,val)
        if iscomment is True:
            dop.comment('__',new_key)

        #preprint_r(dop.getconf('__'))
        new_lines = self._value_to_lines(dop.getconf('__'))
        #print "\n".join(new_lines)

        return new_lines
开发者ID:AdUser,项目名称:karesansui,代码行数:33,代码来源:xml_like_conf_parser.py

示例2: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class iscsidParser:

    _module = "hosts"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})

        self.parser = Parser()
        self.parser.set_delim("[ \t]*=[ \t]*")
        self.parser.set_new_delim(" = ")
        self.parser.set_comment("#")
        self.base_parser_name = self.parser.__class__.__name__
        pass

    def set_footer(self, footer=""):
        self.parser.set_footer(footer)

    def source_file(self):
        retval = [ISCSI_DEFAULT_CONFIG_PATH]

        return retval

    def read_conf(self, conf_path=None, extra_args=None):
        retval = {}

        if conf_path is None:
            conf_path = ISCSI_DEFAULT_CONFIG_PATH

        self.parser.set_source_file([conf_path])
        conf_arr = self.parser.read_conf()
        try:
            self.dop.addconf(self._module,conf_arr[conf_path]['value'])
        except:
            pass

        self.dop.set(self._module,['@BASE_PARSER'],self.base_parser_name)
        #self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)

    def write_conf(self, conf_arr={}, conf_path=None, extra_args=None, dryrun=False):
        retval = True

        if conf_path is None:
            conf_path = ISCSI_DEFAULT_CONFIG_PATH

        try:
            self.dop.addconf("parser",{})
            self.dop.set("parser",[conf_path],conf_arr)
            #self.dop.preprint_r("parser")
            arr = self.dop.getconf("parser")
            self.parser.write_conf(arr,dryrun=dryrun)
        except:
            pass

        return retval
开发者ID:AdUser,项目名称:karesansui,代码行数:58,代码来源:iscsid.py

示例3: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class modprobe_confParser:

    _module = "modprobe_conf"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})

        self.parser = Parser()
        self.parser.set_delim(" ")
        self.parser.set_new_delim(" ")
        self.parser.set_comment("#")
        self.base_parser_name = self.parser.__class__.__name__

        pass

    def source_file(self):
        retval = [PARSER_MODPROBE_CONF]

        return retval

    def read_conf(self,extra_args=None):
        retval = {}

        self.parser.set_source_file([PARSER_MODPROBE_CONF])
        conf_arr = self.parser.read_conf()
        try:
            self.dop.addconf(self._module,conf_arr[PARSER_MODPROBE_CONF]['value'])
        except:
            pass

        self.dop.set(self._module,['@BASE_PARSER'],self.base_parser_name)
        #self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)

    def write_conf(self,conf_arr={},extra_args=None,dryrun=False):
        retval = True

        try:
            self.dop.addconf("parser",{})
            self.dop.set("parser",[PARSER_MODPROBE_CONF],conf_arr)
            #self.dop.preprint_r("parser")
            arr = self.dop.getconf("parser")
            self.parser.write_conf(arr,dryrun=dryrun)
        except:
            pass

        return retval
开发者ID:goura,项目名称:karesansui,代码行数:50,代码来源:modprobe_conf.py

示例4: _PUT

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        host = findbyhost1(self.orm, host_id)
        if not validates_iptables_save(self, host):
            return web.badrequest(self.view.alert)

        from karesansui.lib.dict_op import DictOp
        dop = DictOp()
        dop.addconf("iptables", {})
        dop.set("iptables",["config"],self.input.iptables_save.split("\r\n"))
        retval = write_conf(dop, self, host)
        if retval is False:
            return web.internalerror('Internal Server Error. (Adding Task)')

        return web.accepted(url=web.ctx.path)
开发者ID:AdUser,项目名称:karesansui,代码行数:19,代码来源:hostby1iptables.py

示例5: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class xmlLikeConfParser:

    _delim               = "[ \t]+"
    _new_delim           = " "
    _comment             = "#"
    _reserved_key_prefix = "@"
    _indent              = "  "

    _module  = "xml_like_conf_parser"
    _footer  = "-- Generated by karesansui"

    def __init__(self,paths=[]):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})
        self.set_source_file(paths)

        self.opt_uni   = ['PIDFile']
        self.opt_multi = ['LoadPlugin','Include']
        self.opt_sect  = ['Directory','VirtualHost','View']

    def set_opt_uni(self, opts):
        self.opt_uni = opts

    def set_opt_multi(self, opts):
        self.opt_multi = opts

    def set_opt_sect(self, opts):
        self.opt_sect = opts

    def set_delim(self, delim=" "):
        self._delim = delim

    def set_new_delim(self, delim=" "):
        self._new_delim = delim

    def set_comment(self, comment="#"):
        self._comment = comment

    def set_reserved_key_prefix(self, prefix="@"):
        self._reserved_key_prefix = prefix

    def set_footer(self, footer=""):
        self._footer = footer

    def set_source_file(self,paths=[]):
        if type(paths) == str:
            paths = [paths]
        self.paths = paths
        return True

    def get_source_file(self):
        return self.paths

    def source_file(self):
        return self.get_source_file()

    def build_value(self, value=None, precomment=[], postcomment=None):
        if type(precomment) == str:
            precomment = [precomment]
        return [value, [precomment, postcomment], ]

    def read_conf(self):
        retval = {}
        orders_key = "%sORDERS" % (self._reserved_key_prefix,)

        for _afile in self.source_file():
            res = ConfigFile(_afile).read()
            self.orders = []
            self.dop.set(self._module,[_afile],self._read_conf(res))
            self.dop.set(self._module,[_afile,orders_key],self.orders)

        return self.dop.getconf(self._module)

    def _read_conf(self,lines,level=0):

        dop = DictOp()
        dop.addconf("__",{})

        pre_comment  = []   # 設定の前のコメント リスト配列
        post_comment = None # 設定行のコメント 文字列
        _in_section = False
        _res = []
        for _aline in lines:

            if _in_section is True:
                regex = "[ \t]*(?P<comment>#*)[ \t]*</(?P<key>%s)>" % _section_key #'|'.join(self.opt_sect)
                _regex = re.compile(r"%s" % regex)
                m = _regex.match(_aline)
                if m:
                    _comment = m.group('comment')
                    _key     = m.group('key').strip()
                    values = self.build_value(self._read_conf(_res,level),pre_comment,post_comment)
                    dop.set("__",[_key,_section_val],values)
                    if _comment != "":
                        dop.comment("__",[_key,_section_val])
                    if level == 1:
                        self.orders.append([_key,_section_val])
                    pre_comment  = []
                    post_comment = None
                    _in_section = False
#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:xml_like_conf_parser.py

示例6: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class collectdpluginParser:

    _module = "collectdplugin"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})

        self.parser = Parser()
        self.parser.set_delim("[ \t]+")
        self.parser.set_new_delim("\t")
        self.parser.set_comment("#")
        self.base_parser_name = self.parser.__class__.__name__

        from karesansui.lib.parser.collectd import collectdParser
        collectdp = collectdParser()

        self.parser.set_opt_uni(collectdp.opt_uni)
        self.parser.set_opt_multi(collectdp.opt_multi)
        self.parser.set_opt_sect(collectdp.opt_sect)

        pass

    def set_footer(self, footer=""):
        self.parser.set_footer(footer)

    def source_file(self):
        retval = []

        glob_str = "%s/*.conf" % (PARSER_COLLECTD_PLUGIN_DIR,)
        for _afile in glob.glob(glob_str):
            retval.append(_afile)

        return retval

    def read_conf(self,extra_args=None):
        retval = {}

        for _afile in self.source_file():

            plugin_name = re.sub("\.conf$","",os.path.basename(_afile))

            try:
                extra_args['include']
                if not re.search(extra_args['include'],plugin_name):
                    continue
            except:
                pass

            self.parser.set_source_file([_afile])
            conf_arr = self.parser.read_conf()
            try:
                self.dop.set(self._module,[plugin_name],conf_arr[_afile]['value'])
            except:
                pass

        self.dop.set(self._module,['@BASE_PARSER'],self.base_parser_name)
        #self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)

    def _pre_write_conf(self,conf_arr={}):

        # Change permission to be able to read/write data kss group.
        if os.path.exists(COLLECTD_DATA_DIR):
            if os.getuid() == 0:
                r_chgrp(COLLECTD_DATA_DIR,KARESANSUI_GROUP)
                r_chmod(COLLECTD_DATA_DIR,"g+rwx")
                r_chmod(COLLECTD_DATA_DIR,"o-rwx")

        dop = DictOp()
        dop.addconf("__",conf_arr)

        if dop.isset("__",["python"]) is True:
            dop.cdp_unset("__",["python","Plugin","python","@ORDERS"],multiple_file=True)
            orders = []
            orders.append(['Encoding'])
            orders.append(['LogTraces'])
            orders.append(['Interactive'])
            orders.append(['ModulePath'])
            orders.append(['Import'])
            orders.append(['Module'])
            dop.cdp_set("__",["python","Plugin","python","@ORDERS"],orders,is_opt_multi=True,multiple_file=True)

        return dop.getconf("__")

    def write_conf(self,conf_arr={},extra_args=None,dryrun=False):
        retval = True

        conf_arr = self._pre_write_conf(conf_arr)

        for plugin_name,_v in conf_arr.iteritems():

            _afile = "%s/%s.conf" % (PARSER_COLLECTD_PLUGIN_DIR,plugin_name,)
            try:
                _v['action']
                if _v['action'] == "delete":
                    if os.path.exists(_afile):
                        os.unlink(_afile)
                        continue
            except:
#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:collectdplugin.py

示例7: _read_conf

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
    def _read_conf(self,lines,level=0):

        dop = DictOp()
        dop.addconf("__",{})

        pre_comment  = []   # 設定の前のコメント リスト配列
        post_comment = None # 設定行のコメント 文字列
        _in_section = False
        _res = []
        for _aline in lines:

            if _in_section is True:
                regex = "[ \t]*(?P<comment>#*)[ \t]*</(?P<key>%s)>" % _section_key #'|'.join(self.opt_sect)
                _regex = re.compile(r"%s" % regex)
                m = _regex.match(_aline)
                if m:
                    _comment = m.group('comment')
                    _key     = m.group('key').strip()
                    values = self.build_value(self._read_conf(_res,level),pre_comment,post_comment)
                    dop.set("__",[_key,_section_val],values)
                    if _comment != "":
                        dop.comment("__",[_key,_section_val])
                    if level == 1:
                        self.orders.append([_key,_section_val])
                    pre_comment  = []
                    post_comment = None
                    _in_section = False
                    _res = []
                    level = level - 1
                else:
                    _res.append(_aline)

            else:

                _aline = _aline.rstrip('\r\n')

                if _aline.strip() == "":
                    pre_comment.append(_aline)
                    continue

                match = False
                for _type in ['uni','multi','sect']:
                    exec("regex = '|'.join(self.opt_%s)" % _type)
                    if _type == "sect":
                        regex = "[ \t]*(?P<comment>#*)[ \t]*<(?P<key>%s)(?P<section>.*)>" % regex
                    elif _type == "multi":
                        regex = "[ \t]*(?P<comment>#*)[ \t]*(?P<key>%s)[ \t]+(?P<value>.+)"  % regex
                    elif _type == "uni":
                        regex = "[ \t]*(?P<comment>#*)[ \t]*(?P<key>%s)[ \t]+(?P<value>.+)"  % regex

                    _regex = re.compile(r"%s" % regex)
                    m = _regex.match(_aline)
                    if m:
                        match = True
                        _comment = m.group('comment')
                        _key     = m.group('key').strip()
                        if _type == "sect":
                            _section_key = _key
                            _section_val = re.sub(r"[\"']","",m.group('section').strip())
                            _in_section = True
                            level = level + 1
                        elif _type == "multi":
                            _value = m.group('value').strip()
                            if _value.find(self._comment) > 0:
                                post_comment = _value[_value.find(self._comment):]
                            _value = re.sub("%s$" % post_comment, "", _value).rstrip()
                            values = self.build_value(_value,pre_comment,post_comment)
                            dop.set("__",[_key,_value],values)
                            if _comment != "":
                                dop.comment("__",[_key,_value])
                            if level == 0:
                                self.orders.append([_key,_value])
                            pre_comment  = []
                            post_comment = None
                        elif _type == "uni":
                            _value   = m.group('value').strip()
                            if _value.find(self._comment) > 0:
                                post_comment = _value[_value.find(self._comment):]
                            _value = re.sub("%s$" % post_comment, "", _value).rstrip()
                            values = self.build_value(_value,pre_comment,post_comment)
                            dop.set("__",[_key],values)
                            if _comment != "":
                                dop.comment("__",[_key])
                            if level == 0:
                                self.orders.append([_key])
                            pre_comment  = []
                            post_comment = None
                        break

                if match is False:

                    # ブラケットディレクティブのパラメータは除外する (よって、ブラケットディレクティブは全ての定義が必要!)
                    # example: "<undefined_directive 'foobar'>"
                    regex_exclude1 = "[ \t]*(?P<comment>#*)[ \t]*(?P<key>%s)[ \t]" % '|'.join(self.opt_sect)
                    _regex_exclude1 = re.compile(r"%s" % regex_exclude1)

                    # 未定義のパラメータの値がクオートせずにスペース区切りで3つ以上の値を指定している場合はコメント行とみなす
                    # example: "# Read this configuration file"
                    regex_exclude2 = "[ \t]*#+[ \t]*[^ \t]+([ \t]+[^ \t]+){3,}"
                    _regex_exclude2 = re.compile(r"%s" % regex_exclude2)
#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:xml_like_conf_parser.py

示例8: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class iptablesParser:

    _module = "iptables"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})

        self.parser = Parser()
        self.base_parser_name = self.parser.__class__.__name__
        pass

    def source_file(self):
        retval = [PARSER_IPTABLES_CONF]

        return retval

    def read_conf(self,extra_args=None):
        retval = {}

        self.parser.set_source_file([PARSER_IPTABLES_CONF])
        self.dop.addconf(self._module,{})

        conf_arr = self.parser.read_conf()
        try:
            lines = conf_arr[PARSER_IPTABLES_CONF]['value']
            lint = self.do_lint("\n".join(lines))
            self.dop.set(self._module,["config"],lines)
            self.dop.set(self._module,["lint"]  ,lint)
        except:
            pass

        cmdfile = "cmd:%s" % PARSER_COMMAND_IPTABLES_SAVE
        self.parser.set_source_file([cmdfile])
        conf_arr = self.parser.read_conf()
        try:
            lines = conf_arr[cmdfile]['value']
            self.dop.set(self._module,["status"],lines)
        except:
            pass

        self.parser.set_source_file([PARSER_IPTABLES_CONF])

        self.dop.set(self._module,['@BASE_PARSER'],self.base_parser_name)
        #self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)

    def write_conf(self,conf_arr={},extra_args=None,dryrun=False):
        retval = True

        now = time.strftime("%c",time.localtime())
        try:
            self.dop.addconf("parser",{})

            lines = conf_arr["config"]["value"]
            lines = array_replace(lines,PARSER_IPTABLES_CONF_HEADER,"# Generated by karesansui on %s" % (now,))
            lines = array_replace(lines,PARSER_IPTABLES_CONF_FOOTER,"# Completed on %s" % (now,))
            self.dop.set("parser",[PARSER_IPTABLES_CONF],lines)
            #self.dop.preprint_r("parser")
            arr = self.dop.getconf("parser")
            self.parser.write_conf(arr,dryrun=dryrun)
            self.do_condrestart()
        except:
            pass

        return retval

    def do_start(self):
        return self._do("start")

    def do_stop(self):
        return self._do("stop")

    def do_restart(self):
        return self._do("restart")

    def do_condrestart(self):
        return self._do("condrestart")

    def do_status(self):
        return self._do("status")

    def is_running(self):
        return self.do_status()[0]

    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]

    # reverseがFalseなら設定ファイルをもとに、システムに反映(condrestart)
    # reverseがTrueならシステムの状態をもとに、設定ファイルに反映
    def do_sync(self,reverse=False):
#.........这里部分代码省略.........
开发者ID:goura,项目名称:karesansui,代码行数:103,代码来源:iptables.py

示例9: process

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
    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")

#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:add_bonding.py

示例10: process

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
    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,
#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:delete_bonding.py

示例11: iptablesParser

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
"""
"""
if __name__ == '__main__':
    """Testing
    """
    parser = iptablesParser()
    dop = DictOp()
    dop.addconf("dum",parser.read_conf())
    lines = dop.get("dum",['config'])
    lines.append("aa# test")
    lines.append("bb# test")
    lines.append("aa# test")
    #preprint_r(lines)

    dop.set("dum",['config'],lines)
    conf = dop.getconf("dum")
    #preprint_r(conf)

    parser.do_stop()
    print parser.is_running()
    parser.do_start()
    print parser.is_running()
    parser.do_stop()
    print parser.is_running()

    parser.write_conf(conf,dryrun=True)
    #parser.do_sync(True)
    print parser.do_sync(False)

    contents = open("/etc/sysconfig/iptables.corrupted").read()
开发者ID:goura,项目名称:karesansui,代码行数:32,代码来源:iptables.py

示例12: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class collectdParser:

    _module = "collectd"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})

        self.parser = Parser()
        self.parser.set_delim("[ \t]+")
        self.parser.set_new_delim("\t")
        self.parser.set_comment("#")
        self.base_parser_name = self.parser.__class__.__name__

        self.opt_uni   = ['Hostname',
                          'FQDNLookup',
                          'BaseDir',
                          'PIDFile',
                          'Target',
                          'Host',
                          'Key',
                          'LogLevel',
                          'Plugin',
                          'Subject',
                          'SMTPPort',
                          'SMTPServer',
                          'URL',
                          'Type',
                          'Chain']
        self.opt_multi = ['Include',
                          'LoadPlugin',
                          'Collect',
                          'DriverOption',
                          'GetCapacity',
                          'GetSnapshot',
                          'Irq',
                          'JVMArg',
                          'Listen',
                          'PreCacheChain',
                          'PostCacheChain',
                          'Query',
                          'Recipient',
                          'Sensor',
                          'Server',
                          'WatchAdd']
        self.opt_sect  = ['Plugin',
                          'LoadPlugin',
                          'Threshold',
                          'Type',
                          'Chain',
                          'Data',
                          'Database',
                          'Directory',
                          'Disks',
                          'File',
                          'Host',
                          'Key',
                          'Match',
                          'Metric',
                          'Module',
                          'Page',
                          'Query',
                          'Recursor',
                          'Result',
                          'Router',
                          'Rule',
                          'Server',
                          'System',
                          'Table',
                          'Target',
                          'URL',
                          'View',
                          'VolumePerf',
                          'VolumeUsage',
                          'WAFL']

        self.parser.set_opt_uni(self.opt_uni)
        self.parser.set_opt_multi(self.opt_multi)
        self.parser.set_opt_sect(self.opt_sect)

        pass

    def set_footer(self, footer=""):
        self.parser.set_footer(footer)

    def source_file(self):
        retval = [PARSER_COLLECTD_CONF]

        return retval

    def read_conf(self,extra_args=None):
        retval = {}

        self.parser.set_source_file([PARSER_COLLECTD_CONF])
        conf_arr = self.parser.read_conf()
        try:
            self.dop.addconf(self._module,conf_arr[PARSER_COLLECTD_CONF]['value'])
        except:
            pass

#.........这里部分代码省略.........
开发者ID:AdUser,项目名称:karesansui,代码行数:103,代码来源:collectd.py

示例13: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class staticrouteParser:

    _module = "staticroute"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})
        self.exclude_device_regex = "\.old|\.bak|\.rpm.*|\.20"

        self.parser = Parser()

        self.config_style = self.detect_config_style()
        if self.config_style == "old":
            self.parser.set_delim(" via ")
            self.parser.set_new_delim(" via ")
        else:
            self.parser.set_delim("=")
            self.parser.set_new_delim("=")

        self.base_parser_name = self.parser.__class__.__name__
        pass

    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 source_file(self):
        retval = []

        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:
                retval.append(_afile)

        return retval

    def convert_old_style(self, conf_arr):

        dop = DictOp()
        dop.addconf("__",{})
        orders = []
        for cnt in range(0,20):
            try:
                try:
                    exec("action  = conf_arr['ADDRESS%d']['action']" % cnt)
                except:
                    action = None

                exec("address = conf_arr['ADDRESS%d']['value']" % cnt)
                exec("netmask = conf_arr['NETMASK%d']['value']" % cnt)
                exec("gateway = conf_arr['GATEWAY%d']['value']" % cnt)

                target = "%s/%s" % (address,netmask,)
                net = NetworkAddress(target)
                try:
                    target = net.cidr
                except:
                    pass
                dop.add("__",[target],gateway)

                if action == "delete":
                    dop.delete("__",[target])

                orders.append([target])
            except:
                pass

        if len(orders) != 0:
            dop.add("__",['@ORDERS'],orders)

        return dop.getconf("__")

    def convert_new_style(self, conf_arr):

        dop = DictOp()
        dop.addconf("__",{})
        orders = []

        try:
            old_orders = conf_arr['@ORDERS']['value']
        except:
            old_orders = []

        cnt = 0
#.........这里部分代码省略.........
开发者ID:goura,项目名称:karesansui,代码行数:103,代码来源:staticroute.py

示例14: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class lineParser:

    _comment     = ""

    _module      = "line_parser"

    def __init__(self,paths=[]):
        self.dop = DictOp()
        self.dop.addconf(self._module,{})
        self.set_source_file(paths)

    def set_comment(self, comment=""):
        self._comment = comment

    def set_source_file(self,paths=[]):
        if type(paths) == str:
            paths = [paths]
        self.paths = paths
        return True

    def get_source_file(self):
        return self.paths

    def source_file(self):
        return self.get_source_file()

    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 write_conf(self,conf_arr={},dryrun=False):
        retval = True

        for _path,_v in conf_arr.iteritems():

            if _path[0:1] != "/":
                continue

            try:
                _v['value']
            except:
                continue

            if dryrun is False:
                ConfigFile(_path).write("\n".join(_v['value']) + "\n")
            else:
                print "\n".join(_v['value'])

        return retval
开发者ID:goura,项目名称:karesansui,代码行数:69,代码来源:line_parser.py

示例15: __init__

# 需要导入模块: from karesansui.lib.dict_op import DictOp [as 别名]
# 或者: from karesansui.lib.dict_op.DictOp import set [as 别名]
class ifcfgParser:

    _module = "ifcfg"

    def __init__(self):
        self.dop = DictOp()
        self.dop.addconf(self._module, {})

        self.parser = Parser()
        self.exclude_device_regex = "\.old|\.bak|\.rpm.*|lo|\.20"
        self.exclude_device_regex = "\.old|\.bak|\.rpm.*|\.20"
        self.base_parser_name = self.parser.__class__.__name__
        pass

    def source_file(self):
        retval = []

        glob_str = "%s/%s" % (PARSER_IFCFG_DIR, PARSER_IFCFG_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:
                retval.append(_afile)

        return retval

    def read_conf(self, extra_args=None):
        retval = {}

        for _afile in self.source_file():

            device_name = os.path.basename(_afile).replace(PARSER_IFCFG_FILE_PREFIX, "")
            self.parser.set_source_file([_afile])
            conf_arr = self.parser.read_conf()
            try:
                self.dop.set(self._module, [device_name], conf_arr[_afile]["value"])
            except:
                pass

        self.dop.set(self._module, ["@BASE_PARSER"], self.base_parser_name)
        # self.dop.preprint_r(self._module)
        return self.dop.getconf(self._module)

    def write_conf(self, conf_arr={}, extra_args=None, dryrun=False):
        retval = True

        for device_name, _v in conf_arr.iteritems():

            _afile = "%s/%s%s" % (PARSER_IFCFG_DIR, PARSER_IFCFG_FILE_PREFIX, device_name)
            try:
                _v["action"]
                if _v["action"] == "delete":
                    if os.path.exists(_afile):
                        os.unlink(_afile)
                        # pass
            except:
                continue

            try:
                _v["value"]

                self.dop.addconf("parser", {})
                self.dop.set("parser", [_afile], _v["value"])
                # self.dop.preprint_r("parser")
                arr = self.dop.getconf("parser")
                self.parser.write_conf(arr, dryrun=dryrun)
            except:
                pass

        return retval
开发者ID:nabeken,项目名称:karesansui,代码行数:71,代码来源:ifcfg.py


注:本文中的karesansui.lib.dict_op.DictOp.set方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。