コード例 #1
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        bond_list = get_bonding_info()

        if self.is_mode_input() is True:
            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.view.create_bond_name = "bond%s" % (exist_bond_max_num + 1)
            dev_list = get_ifconfig_info("regex:^eth")
            for bond in bond_list:
                for slave in bond_list[bond]['slave']:
                    if slave in dev_list:
                        dev_list[slave]['bond'] = bond

            #pysical_dev_list = get_ifconfig_info("regex:^peth")
            pysical_dev_list = get_ifconfig_info("regex:^br")
            for pysical_dev in pysical_dev_list:
                if pysical_dev[1:] in dev_list:
                    dev_list[pysical_dev[1:]]['bridge'] = pysical_dev

            self.view.bond_target_dev = dev_list
            self.view.hypervisors = available_virt_mechs()
            return True

        dev_list = get_ifconfig_info()

        for bond in bond_list:
            if bond in dev_list:
                dev_list[bond]['bond'] = True
                for slave in bond_list[bond]['slave']:
                    for dev in dev_list:
                        if dev == slave:
                            dev_list[dev]['bond'] = True

        self.view.current = dev_list
        self.view.bond_list = bond_list

        return True
コード例 #2
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        bond_list = get_bonding_info()

        if self.is_mode_input() is True:
            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.view.create_bond_name = "bond%s" % (exist_bond_max_num + 1)
            dev_list = get_ifconfig_info("regex:^eth")
            for bond in bond_list:
                for slave in bond_list[bond]['slave']:
                    if slave in dev_list:
                        dev_list[slave]['bond'] = bond

            #pysical_dev_list = get_ifconfig_info("regex:^peth")
            pysical_dev_list = get_ifconfig_info("regex:^br")
            for pysical_dev in pysical_dev_list:
                if pysical_dev[1:] in dev_list:
                    dev_list[pysical_dev[1:]]['bridge'] = pysical_dev

            self.view.bond_target_dev = dev_list
            self.view.hypervisors = available_virt_mechs()
            return True

        dev_list = get_ifconfig_info()

        for bond in bond_list:
            if bond in dev_list:
                dev_list[bond]['bond'] = True
                for slave in bond_list[bond]['slave']:
                    for dev in dev_list:
                        if dev == slave:
                            dev_list[dev]['bond'] = True

        self.view.current = dev_list
        self.view.bond_list = bond_list

        return True
コード例 #3
0
ファイル: console.py プロジェクト: fkei/karesansui
    def _GET(self, *param, **params):
        _prep_console()

        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        model = findbyguest1(self.orm, guest_id)
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.notfound()

            dom = kvc.search_guests(domname)[0]

            document = XMLParse(dom.XMLDesc(1))

            self.view.graphics_port = XMLXpath(document,
                                          '/domain/devices/graphics/@port')
            self.view.xenname = XMLXpath(document,
                                         '/domain/name/text()')
        finally:
            kvc.close()

        h_model = findbyhost1(self.orm, host_id)
        try:
            from karesansui.lib.utils import get_ifconfig_info
            device = KVM_BRIDGE_PREFIX + "0"
            self.view.host_ipaddr = get_ifconfig_info(device)[device]["ipaddr"]
        except:
            try:
                self.view.host_ipaddr = h_model.hostname.split(":")[0].strip()
            except:
                self.view.host_ipaddr = socket.gethostbyname(socket.gethostname())

        return True
コード例 #4
0
    def _GET(self, *param, **params):

        java_dir = karesansui.dirname + '/static/java'
        self.view.applet_dst_path = java_dir + '/VncViewer.jar'
        self.view.applet_src_path = _get_applet_source_path()
        self.view.found_applet_located = os.path.exists(
            self.view.applet_dst_path)

        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        model = findbyguest1(self.orm, guest_id)
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.notfound()

            dom = kvc.search_guests(domname)[0]

            document = XMLParse(dom.XMLDesc(1))

            self.view.graphics_port = XMLXpath(
                document, '/domain/devices/graphics/@port')
            self.view.xenname = XMLXpath(document, '/domain/name/text()')
        finally:
            kvc.close()

        h_model = findbyhost1(self.orm, host_id)
        try:
            from karesansui.lib.utils import get_ifconfig_info
            device = KVM_BRIDGE_PREFIX + "0"
            self.view.host_ipaddr = get_ifconfig_info(device)[device]["ipaddr"]
        except:
            try:
                self.view.host_ipaddr = h_model.hostname.split(":")[0].strip()
            except:
                self.view.host_ipaddr = socket.gethostbyname(
                    socket.gethostname())

        return True
コード例 #5
0
ファイル: console.py プロジェクト: karesansui/karesansui
    def _GET(self, *param, **params):

        java_dir = karesansui.dirname + "/static/java"
        self.view.applet_dst_path = java_dir + "/VncViewer.jar"
        self.view.applet_src_path = _get_applet_source_path()
        self.view.found_applet_located = os.path.exists(self.view.applet_dst_path)

        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None:
            return web.notfound()

        model = findbyguest1(self.orm, guest_id)
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname:
                return web.notfound()

            dom = kvc.search_guests(domname)[0]

            document = XMLParse(dom.XMLDesc(1))

            self.view.graphics_port = XMLXpath(document, "/domain/devices/graphics/@port")
            self.view.xenname = XMLXpath(document, "/domain/name/text()")
        finally:
            kvc.close()

        h_model = findbyhost1(self.orm, host_id)
        try:
            from karesansui.lib.utils import get_ifconfig_info

            device = KVM_BRIDGE_PREFIX + "0"
            self.view.host_ipaddr = get_ifconfig_info(device)[device]["ipaddr"]
        except:
            try:
                self.view.host_ipaddr = h_model.hostname.split(":")[0].strip()
            except:
                self.view.host_ipaddr = socket.gethostbyname(socket.gethostname())

        return True
コード例 #6
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        self.view.current = get_ifconfig_info()

        modules = ["network", "resolv", "hosts"]

        host = findbyhost1(self.orm, host_id)
        dop = read_conf(modules, self, host)
        if dop is False:
            return web.internalerror('Internal Server Error. (Timeout)')

        self.view.gateway = dop.get("network", ["GATEWAY"])
        self.view.search = dop.get("resolv", ["search"])

        self.view.nameserver = dop.get("resolv", ["nameserver"])
        if self.view.nameserver is False:
            self.view.nameserver = []
        if type(self.view.nameserver) == str:
            self.view.nameserver = [self.view.nameserver]
        self.view.nameserver = "\n".join(self.view.nameserver)

        self.view.domainname = dop.get("resolv", ["domain"])
        if self.view.domainname is False:
            self.view.domainname = dop.get("network", ["DOMAINNAME"])
        if self.view.domainname is False:
            self.view.domainname = re.sub("^[^\.]+\.", "", os.uname()[1])

        self.view.hostname = dop.get("network", ["HOSTNAME"])
        if self.view.hostname is False:
            self.view.hostname = os.uname()[1]

        self.view.hostname_short = re.sub("\.%s$" % (self.view.domainname), "",
                                          self.view.hostname)

        # --
        return True
コード例 #7
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        self.view.current = get_ifconfig_info()

        modules = ["network","resolv","hosts"]

        host = findbyhost1(self.orm, host_id)
        dop = read_conf(modules, self, host)
        if dop is False:
            return web.internalerror('Internal Server Error. (Timeout)')

        self.view.gateway    = dop.get("network",["GATEWAY"])
        self.view.search     = dop.get("resolv" ,["search"])

        self.view.nameserver = dop.get("resolv" ,["nameserver"])
        if self.view.nameserver is False:
            self.view.nameserver = []
        if type(self.view.nameserver) == str:
            self.view.nameserver = [self.view.nameserver]
        self.view.nameserver = "\n".join(self.view.nameserver)

        self.view.domainname  = dop.get("resolv" ,["domain"])
        if self.view.domainname is False:
            self.view.domainname = dop.get("network" ,["DOMAINNAME"])
        if self.view.domainname is False:
            self.view.domainname = re.sub("^[^\.]+\.","",os.uname()[1])

        self.view.hostname = dop.get("network" ,["HOSTNAME"])
        if self.view.hostname is False:
            self.view.hostname = os.uname()[1]

        self.view.hostname_short = re.sub("\.%s$" % (self.view.domainname), "", self.view.hostname)

        # --
        return True
コード例 #8
0
ファイル: hostby1iptables.py プロジェクト: AdUser/karesansui
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        self.view.current = get_ifconfig_info()

        modules = ["iptables"]

        host = findbyhost1(self.orm, host_id)
        dop = read_conf(modules, self, host)
        if dop is False:
            return web.internalerror('Internal Server Error. (Timeout)')

        config = dop.get("iptables",["config"])
        status = dop.get("iptables",["status"])
        lint   = dop.get("iptables",["lint"])

        policies = {}
        for _aline in status:
            m = re.match("\*(?P<table>[a-z]+)",_aline.rstrip())
            if m:
                table = m.group("table")
                policies[table] = {}
            else:
                m = re.match(":(?P<chain>[A-Z]+) +(?P<policy>[A-Z]+)",_aline.rstrip())
                if m:
                    chain  = m.group("chain")
                    policy = m.group("policy")
                    policies[table][chain] = policy

        self.view.config   = "\n".join(config)
        self.view.status   = "\n".join(status)
        self.view.lint     = lint
        self.view.policies = policies
        self.view.result_js  = ""

        return True
コード例 #9
0
ファイル: guest.py プロジェクト: fkei/karesansui
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)
        uris = available_virt_uris()

        self.kvc = KaresansuiVirtConnection()
        try: # libvirt connection scope -->
            # Storage Pool
            #inactive_pool = self.kvc.list_inactive_storage_pool()
            inactive_pool = []
            active_pool = self.kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            if not pools:
                return web.badrequest('One can not start a storage pool.')

            # Output .input
            if self.is_mode_input() is True:
                self.view.pools = pools
                pools_info = {}
                pools_vols_info = {}
                pools_iscsi_blocks = {}
                already_vols = []
                guests = []

                guests += self.kvc.list_inactive_guest()
                guests += self.kvc.list_active_guest()
                for guest in guests:
                    already_vol = self.kvc.get_storage_volume_bydomain(domain=guest,
                                                                       image_type=None,
                                                                       attr='path')
                    if already_vol:
                        already_vols += already_vol.keys()

                for pool in pools:
                    pool_obj = self.kvc.search_kvn_storage_pools(pool)[0]
                    if pool_obj.is_active() is True:
                        pools_info[pool] = pool_obj.get_info()

                        blocks = None
                        if pools_info[pool]['type'] == 'iscsi':
                            blocks = self.kvc.get_storage_volume_iscsi_block_bypool(pool)
                            if blocks:
                                pools_iscsi_blocks[pool] = []
                        vols_obj = pool_obj.search_kvn_storage_volumes(self.kvc)
                        vols_info = {}

                        for vol_obj in vols_obj:
                            vol_name = vol_obj.get_storage_volume_name()
                            vols_info[vol_name] = vol_obj.get_info()
                            if blocks:
                                if vol_name in blocks and vol_name not in already_vols:
                                    pools_iscsi_blocks[pool].append(vol_obj.get_info())

                        pools_vols_info[pool] = vols_info

                self.view.pools_info = pools_info
                self.view.pools_vols_info = pools_vols_info
                self.view.pools_iscsi_blocks = pools_iscsi_blocks

                bridge_prefix = {
                    "XEN":"xenbr",
                    "KVM":KVM_BRIDGE_PREFIX,
                    }
                self.view.host_id = host_id
                self.view.DEFAULT_KEYMAP = DEFAULT_KEYMAP
                self.view.DISK_NON_QEMU_FORMAT = DISK_NON_QEMU_FORMAT
                self.view.DISK_QEMU_FORMAT = DISK_QEMU_FORMAT

                self.view.hypervisors = {}
                self.view.mac_address = {}
                self.view.keymaps = {}
                self.view.phydev = {}
                self.view.virnet = {}

                used_ports = {}

                for k,v in MACHINE_HYPERVISOR.iteritems():
                    if k in available_virt_mechs():
                        self.view.hypervisors[k] = v
                        uri = uris[k]
                        mem_info = self.kvc.get_mem_info()
                        active_networks = self.kvc.list_active_network()
                        used_graphics_ports = self.kvc.list_used_graphics_port()
                        bus_types = self.kvc.bus_types
                        self.view.bus_types = bus_types
                        self.view.max_mem = mem_info['host_max_mem']
                        self.view.free_mem = mem_info['host_free_mem']
                        self.view.alloc_mem = mem_info['guest_alloc_mem']

                        self.view.mac_address[k] = generate_mac_address(k)
                        self.view.keymaps[k] = eval("get_keymaps(%s_KEYMAP_DIR)" % k)

                        # Physical device
                        phydev = []
                        phydev_regex = re.compile(r"%s" % bridge_prefix[k])
                        for dev,dev_info in get_ifconfig_info().iteritems():
                            try:
                                if phydev_regex.match(dev):
                                    phydev.append(dev)
                            except:
                                pass
                        if len(phydev) == 0:
                            phydev.append("%s0" % bridge_prefix[k])
                        phydev.sort()
                        self.view.phydev[k] = phydev # Physical device

                        # Virtual device
                        self.view.virnet[k] = sorted(active_networks)
                        used_ports[k] = used_graphics_ports


                exclude_ports = []
                for k, _used_port in used_ports.iteritems():
                    exclude_ports = exclude_ports + _used_port
                    exclude_ports = sorted(exclude_ports)
                    exclude_ports = [p for p, q in zip(exclude_ports, exclude_ports[1:] + [None]) if p != q]
                self.view.graphics_port = next_number(GRAPHICS_PORT_MIN_NUMBER,
                                                 PORT_MAX_NUMBER,
                                                 exclude_ports)

            else: # .part
                models = findbyhost1guestall(self.orm, host_id)
                guests = []
                if models:
                    # Physical Guest Info
                    self.view.hypervisors = {}
                    for model in models:
                        for k,v in MACHINE_HYPERVISOR.iteritems():
                            if k in available_virt_mechs():
                                self.view.hypervisors[k] = v
                                uri = uris[k]
                                if hasattr(self, "kvc") is not True:
                                    self.kvc = KaresansuiVirtConnection(uri)
                                domname = self.kvc.uuid_to_domname(model.uniq_key)
                                #if not domname: return web.conflict(web.ctx.path)
                                _virt = self.kvc.search_kvg_guests(domname)
                                if 0 < len(_virt):
                                    guests.append(MergeGuest(model, _virt[0]))
                                else:
                                    guests.append(MergeGuest(model, None))

                # Exported Guest Info
                exports = {}
                for pool_name in pools:
                    files = []

                    pool = self.kvc.search_kvn_storage_pools(pool_name)
                    path = pool[0].get_info()["target"]["path"]

                    if os.path.exists(path):
                        for _afile in glob.glob("%s/*/info.dat" % (path,)):
                            param = ExportConfigParam()
                            param.load_xml_config(_afile)

                            _dir = os.path.dirname(_afile)

                            uuid = param.get_uuid()
                            name = param.get_domain()
                            created = param.get_created()
                            title = param.get_title()
                            if title != "":
                                title = re.sub("[\r\n]","",title)
                            if title == "":
                                title = _('untitled')

                            if created != "":
                                created_str = time.strftime("%Y/%m/%d %H:%M:%S", \
                                                            time.localtime(float(created)))
                            else:
                                created_str = _("N/A")

                            files.append({"dir": _dir,
                                          "pool" : pool_name,
                                          #"b64dir" : base64_encode(_dir),
                                          "uuid" : uuid,
                                          "name" : name,
                                          "created" : int(created),
                                          "created_str" : created_str,
                                          "title" : title,
                                          "icon" : param.get_database()["icon"],
                                          })

                    exports[pool_name] = files

                # .json
                if self.is_json() is True:
                    guests_json = []
                    for x in guests:
                        guests_json.append(x.get_json(self.me.languages))

                    self.view.guests = json_dumps(guests_json)
                else:
                    self.view.exports = exports
                    self.view.guests = guests

            return True
        finally:
            #self.kvc.close()
            pass # libvirt connection scope --> Guest#_post()
コード例 #10
0
ファイル: add_bonding.py プロジェクト: AdUser/karesansui
    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
コード例 #11
0
ファイル: hostby1firewall.py プロジェクト: goura/karesansui
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        
        kit = KaresansuiIpTables()
        
        if os.path.exists(kit.firewall_xml_file) is False:
            self.view.have_config = False
        else:
            kit.firewall_xml = kit.read_firewall_xml()
            # --
            self.view.iptables = Storage(
                is_running=kit.is_running(),
                is_configured=kit.is_configured(),
                )
            self.view.have_config = True

            if self.is_mode_input() is True:

                self.view.default_rule_id = len(kit.get_rules()) + 1
                self.view.targets = kit.basic_targets['filter']
                self.view.protocols = kit.chain_protos
                devtype_regexs = {
                    "phy":"^(lo|eth)",
                    "vir":"^(xenbr|virbr|vif|veth)",
                    }
                devtype_phy_regex = re.compile(r"%s" % devtype_regexs['phy'])
                devtype_vir_regex = re.compile(r"%s" % devtype_regexs['vir'])
                
                devs = {}
                devs['phy'] = []
                devs['vir'] = []
                devs['oth'] = []
                cidrs = []
                ips = []
                for dev,dev_info in get_ifconfig_info().iteritems():
                    try:
                        if devtype_phy_regex.match(dev):
                            devs['phy'].append(dev)
                        elif devtype_vir_regex.match(dev):
                            devs['vir'].append(dev)
                        else:
                            devs['oth'].append(dev)
                        
                        if dev_info['ipaddr'] is not None:
                            if not dev_info['ipaddr'] in ips:
                                ips.append(dev_info['ipaddr'])
                        if dev_info['cidr'] is not None:
                            if not dev_info['cidr'] in cidrs:
                                cidrs.append(dev_info['cidr'])
                    except:
                        pass
                devs['phy'].sort()
                devs['vir'].sort()
                devs['oth'].sort()
                self.view.devs = [{'Physical' : devs['phy']},
                                  {'Virtual' : devs['vir']},
                                  {'Other' : devs['oth']},
                                  ]
                
                self.view.cidrs = cidrs
                self.view.ips = ips

        # --
        return True
コード例 #12
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        host = findbyhost1(self.orm, host_id)

        self.view.host_id = host_id

        # unremovable entries
        excludes = {
            "device": ["^peth", "^virbr", "^sit", "^xenbr", "^lo", "^br"],
            "ipaddr": ["^0\.0\.0\.0$", "^169\.254\.0\.0$"],
        }

        devices = []
        phydev_regex = re.compile(r"^eth[0-9]+")
        for dev, dev_info in get_ifconfig_info().iteritems():
            if phydev_regex.match(dev):
                try:
                    if dev_info['ipaddr'] is not None:
                        devices.append(dev)
                        net = NetworkAddress("%s/%s" % (
                            dev_info['ipaddr'],
                            dev_info['mask'],
                        ))
                        excludes['ipaddr'].append(net.network)
                except:
                    pass

        self.view.devices = devices

        parser = Parser()
        status = parser.do_status()
        routes = {}
        for _k, _v in status.iteritems():
            for _k2, _v2 in _v.iteritems():
                name = base64_encode("%s@%s" % (
                    _k2,
                    _k,
                ))
                routes[name] = {}
                routes[name]['name'] = name
                routes[name]['device'] = _k
                routes[name]['gateway'] = _v2['gateway']
                routes[name]['flags'] = _v2['flags']
                routes[name]['ref'] = _v2['ref']
                routes[name]['use'] = _v2['use']
                net = NetworkAddress(_k2)
                routes[name]['ipaddr'] = net.ipaddr
                routes[name]['netlen'] = net.netlen
                routes[name]['netmask'] = net.netmask

                removable = True
                for _ex_key, _ex_val in excludes.iteritems():
                    ex_regex = "|".join(_ex_val)
                    mm = re.search(ex_regex, routes[name][_ex_key])
                    if mm:
                        removable = False

                routes[name]['removable'] = removable

        self.view.routes = routes

        if self.is_mode_input():
            pass

        return True
コード例 #13
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        host = findbyhost1(self.orm, host_id)

        self.view.host_id = host_id

        # unremovable entries
        excludes = {
                   "device": ["^peth","^virbr","^sit","^xenbr","^lo","^br"],
                   "ipaddr": ["^0\.0\.0\.0$", "^169\.254\.0\.0$"],
                   }

        devices = []
        phydev_regex = re.compile(r"^eth[0-9]+")
        for dev,dev_info in get_ifconfig_info().iteritems():
            if phydev_regex.match(dev):
                try:
                    if dev_info['ipaddr'] is not None:
                        devices.append(dev)
                        net = NetworkAddress("%s/%s" % (dev_info['ipaddr'],dev_info['mask'],))
                        excludes['ipaddr'].append(net.network)
                except:
                    pass

        self.view.devices = devices

        parser = Parser()
        status = parser.do_status()
        routes = {}
        for _k,_v in status.iteritems():
            for _k2,_v2 in _v.iteritems():
                name = base64_encode("%s@%s" % (_k2,_k,))
                routes[name] = {}
                routes[name]['name']    = name
                routes[name]['device']  = _k
                routes[name]['gateway'] = _v2['gateway']
                routes[name]['flags']   = _v2['flags']
                routes[name]['ref']     = _v2['ref']
                routes[name]['use']     = _v2['use']
                net = NetworkAddress(_k2)
                routes[name]['ipaddr']  = net.ipaddr
                routes[name]['netlen']  = net.netlen
                routes[name]['netmask'] = net.netmask

                removable = True
                for _ex_key,_ex_val in excludes.iteritems():
                    ex_regex = "|".join(_ex_val)
                    mm = re.search(ex_regex,routes[name][_ex_key])
                    if mm:
                        removable = False

                routes[name]['removable'] = removable

        self.view.routes = routes

        if self.is_mode_input():
            pass

        return True
コード例 #14
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id

        kit = KaresansuiIpTables()

        if os.path.exists(kit.firewall_xml_file) is False:
            self.view.have_config = False
        else:
            kit.firewall_xml = kit.read_firewall_xml()
            # --
            self.view.iptables = Storage(
                is_running=kit.is_running(),
                is_configured=kit.is_configured(),
            )
            self.view.have_config = True

            if self.is_mode_input() is True:

                self.view.default_rule_id = len(kit.get_rules()) + 1
                self.view.targets = kit.basic_targets['filter']
                self.view.protocols = kit.chain_protos
                devtype_regexs = {
                    "phy": "^(lo|eth)",
                    "vir": "^(xenbr|virbr|vif|veth)",
                }
                devtype_phy_regex = re.compile(r"%s" % devtype_regexs['phy'])
                devtype_vir_regex = re.compile(r"%s" % devtype_regexs['vir'])

                devs = {}
                devs['phy'] = []
                devs['vir'] = []
                devs['oth'] = []
                cidrs = []
                ips = []
                for dev, dev_info in get_ifconfig_info().iteritems():
                    try:
                        if devtype_phy_regex.match(dev):
                            devs['phy'].append(dev)
                        elif devtype_vir_regex.match(dev):
                            devs['vir'].append(dev)
                        else:
                            devs['oth'].append(dev)

                        if dev_info['ipaddr'] is not None:
                            if not dev_info['ipaddr'] in ips:
                                ips.append(dev_info['ipaddr'])
                        if dev_info['cidr'] is not None:
                            if not dev_info['cidr'] in cidrs:
                                cidrs.append(dev_info['cidr'])
                    except:
                        pass
                devs['phy'].sort()
                devs['vir'].sort()
                devs['oth'].sort()
                self.view.devs = [
                    {
                        'Physical': devs['phy']
                    },
                    {
                        'Virtual': devs['vir']
                    },
                    {
                        'Other': devs['oth']
                    },
                ]

                self.view.cidrs = cidrs
                self.view.ips = ips

        # --
        return True
コード例 #15
0
    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
コード例 #16
0
ファイル: guestby1device.py プロジェクト: AdUser/karesansui
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        bridge_prefix = {
                          "XEN":"xenbr",
                          "KVM":"br|bondbr",
                          #"KVM":"eth|bondbr",
                        }

        model = findbyguest1(self.orm, guest_id)

        # virt
        self.kvc = KaresansuiVirtConnection()
        try:
            domname = self.kvc.uuid_to_domname(model.uniq_key)
            if not domname:
                return web.notfound()
            virt = self.kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            self.view.guest = guest

            # Output .input
            if self.is_mode_input() is True:
                try:
                    VMType = guest.info["virt"].get_info()["VMType"].upper()
                except:
                    VMType = "KVM"

                self.view.VMType = VMType

                # Network
                phydev = []
                phydev_regex = re.compile(r"%s" % bridge_prefix[VMType])

                for dev,dev_info in get_ifconfig_info().iteritems():
                    try:
                        if phydev_regex.match(dev):
                            phydev.append(dev)
                    except:
                        pass
                if len(phydev) == 0:
                    phydev.append("%s0" % bridge_prefix[VMType])

                phydev.sort()
                self.view.phydev = phydev # Physical device
                self.view.virnet = sorted(self.kvc.list_active_network()) # Virtual device
                self.view.mac_address = generate_mac_address() # new mac address

                # Disk
                inactive_pool = []
                active_pool = self.kvc.list_active_storage_pool()
                pools = inactive_pool + active_pool
                pools.sort()

                if not pools:
                    return web.badrequest('One can not start a storage pool.')

                pools_info = {}
                pools_vols_info = {}
                pools_iscsi_blocks = {}
                already_vols = []
                guests = []

                guests += self.kvc.list_inactive_guest()
                guests += self.kvc.list_active_guest()
                for guest in guests:
                    already_vol = self.kvc.get_storage_volume_bydomain(domain=guest,
                                                                       image_type=None,
                                                                       attr='path')
                    if already_vol:
                        already_vols += already_vol.keys()

                for pool in pools:
                    pool_obj = self.kvc.search_kvn_storage_pools(pool)[0]
                    if pool_obj.is_active() is True:
                        pools_info[pool] = pool_obj.get_info()

                        blocks = None
                        if pools_info[pool]['type'] == 'iscsi':
                            blocks = self.kvc.get_storage_volume_iscsi_block_bypool(pool)
                            if blocks:
                                pools_iscsi_blocks[pool] = []
                        vols_obj = pool_obj.search_kvn_storage_volumes(self.kvc)
                        vols_info = {}

                        for vol_obj in vols_obj:
                            vol_name = vol_obj.get_storage_volume_name()
                            vols_info[vol_name] = vol_obj.get_info()
                            if blocks:
                                if vol_name in blocks and vol_name not in already_vols:
                                    pools_iscsi_blocks[pool].append(vol_obj.get_info())

                        pools_vols_info[pool] = vols_info

                self.view.pools = pools
                self.view.pools_info = pools_info
                self.view.pools_vols_info = pools_vols_info
                self.view.pools_iscsi_blocks = pools_iscsi_blocks

                if VMType == "KVM":
                    self.view.DISK_FORMATS = DISK_QEMU_FORMAT
                else:
                    self.view.DISK_FORMATS = DISK_NON_QEMU_FORMAT

                self.view.bus_types = self.kvc.bus_types

            else: # .part
                self.view.ifinfo = virt.get_interface_info() # interface info
                self.view.disk_info = virt.get_disk_info() # Disk info

        finally:
            self.kvc.close()

        return True
コード例 #17
0
    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
コード例 #18
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        rule_id = param[1]
        if not validates_param_id(self, rule_id):
            return web.notfound(self.view.alert)

        kit = KaresansuiIpTables()
        kit.firewall_xml = kit.read_firewall_xml()

        rules = kit.get_rules()
        cnt = 1
        for rule in rules:
            if cnt == int(rule_id):
                self.view.rule = rule
                break
            cnt = cnt + 1

        if self.is_mode_input():
            self.view.targets = kit.basic_targets['filter']
            self.view.protocols = kit.chain_protos
            self.view.netinfo = get_ifconfig_info()
            devtype_regexs = {
                "phy":"^(lo|eth)",
                "vir":"^(xenbr|virbr|vif|veth)",
                }
            devtype_phy_regex = re.compile(r"%s" % devtype_regexs['phy'])
            devtype_vir_regex = re.compile(r"%s" % devtype_regexs['vir'])

            devs = {}
            devs['phy'] = []
            devs['vir'] = []
            devs['oth'] = []
            cidrs = []
            ips = []
            for dev,dev_info in get_ifconfig_info().iteritems():
                try:
                    if devtype_phy_regex.match(dev):
                        devs['phy'].append(dev)
                    elif devtype_vir_regex.match(dev):
                        devs['vir'].append(dev)
                    else:
                        devs['oth'].append(dev)
                    if dev_info['ipaddr'] is not None:
                        if not dev_info['ipaddr'] in ips:
                            ips.append(dev_info['ipaddr'])
                    if dev_info['cidr'] is not None:
                        if not dev_info['cidr'] in cidrs:
                            cidrs.append(dev_info['cidr'])
                except:
                    pass
            devs['phy'].sort()
            devs['vir'].sort()
            devs['oth'].sort()
            self.view.devs = [{'Physical' : devs['phy']},
                              {'Virtual' : devs['vir']},
                              {'Other' : devs['oth']},
                              ]
            self.view.cidrs = cidrs
            self.view.ips = ips
            return True
        else:
            return web.nomethod()
コード例 #19
0
ファイル: hostby1reportby1.py プロジェクト: goura/karesansui
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()
        self.view.host_id = host_id

        target = param[1]
        if target is None: return web.notfound()
        self.view.target = target

        group_display = False
        dev_list = []
        graph_type = []
        rrd = RRD()
        if target == "cpu":
            for dev in range(0, len(get_proc_cpuinfo())):
                if rrd.check_rrd_file_exist("cpu", dev):
                    dev_list.append(dev)
            graph_type = ['default']
        elif target == "memory":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "df":
            df_list = get_fs_info()
            for fs in df_list:
                if COLLECTD_DF_RRPORT_BY_DEVICE is True:
                    dev = fs['Filesystem']
                    dev = re.sub(r'^/dev/', '', dev)
                    dev = re.sub(r'/', '_', dev)
                else:
                    dev = fs['Mounted']
                    if dev == "/":
                        dev = "root"
                    else:
                        dev = re.sub(r'^/', '', dev)
                        dev = re.sub(r'/', '_', dev)
                if rrd.check_rrd_file_exist("df", dev):
                    dev_list.append(dev)
            graph_type = ['default']

        elif target == "disk":
            group_display = True
            disk_list = get_hdd_list()
            for disk in disk_list:
                dev = disk
                dev = re.sub(r'^/dev/', '', dev)
                if rrd.check_rrd_file_exist("disk", dev):
                    dev_list.append(dev)
            graph_type = ['merged', 'octets', 'ops', 'time']

        elif target == "interface":
            group_display = True
            if_list = get_ifconfig_info().keys()
            for dev in if_list:
                if rrd.check_rrd_file_exist("interface", dev):
                    dev_list.append(dev)
            graph_type = ['packets', 'octets', 'errors']

        elif target == "load":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "uptime":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "users":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "libvirt":
            virt_cpu_type = ['default']
            virt_disk_type = ['octets', 'ops']
            virt_interface_type = ['packets', 'octets', 'errors', 'dropped']
            virt_list = {}
            virt_file_exist = {}

            try:
                kvc = KaresansuiVirtConnection()

                for domname in get_dom_list():
                    virt_list[domname] = {}

                    if rrd.set_rrd_dir_host(domname) is False:
                        virt_file_exist[domname] = False
                        continue

                    try:
                        virt = kvc.search_kvg_guests(domname)[0]
                    except:
                        virt_file_exist[domname] = False
                        continue

                    virt_list[domname]['vcpu'] = {}
                    if rrd.check_rrd_file_exist("libvirt", "total", "vcpu"):
                        virt_list[domname]['vcpu']['total'] = virt_cpu_type
                    for i in range(virt.get_vcpus_info()['max_vcpus']):
                        if rrd.check_rrd_file_exist("libvirt", i, "vcpu"):
                            virt_list[domname]['vcpu'][i] = virt_cpu_type

                    virt_list[domname]['disk'] = {}
                    for disk in virt.get_disk_info():
                        if rrd.check_rrd_file_exist("libvirt", disk['target']['dev'], "disk"):
                            virt_list[domname]['disk'][disk['target']['dev']] = virt_disk_type

                    virt_list[domname]['interface'] = {}
                    for net_dev in virt.get_interface_info():
                        if rrd.check_rrd_file_exist("libvirt", net_dev['target']['dev'], "interface"):
                            virt_list[domname]['interface'][net_dev['target']['dev']] = virt_interface_type

                    if virt_list[domname]['vcpu'] == {} and \
                            virt_list[domname]['disk'] == {} and \
                            virt_list[domname]['interface'] == {}:
                        virt_list[domname] = {}
                        virt_file_exist[domname] = False
                    else:
                        virt_file_exist[domname] = True

            finally:
                kvc.close()

            self.view.virt_list = virt_list
            self.view.virt_file_exist = virt_file_exist

        self.view.group_display = group_display
        dev_list.sort()
        self.view.dev_list = dev_list
        self.view.graph_type = graph_type

        return True
コード例 #20
0
ファイル: delete_bonding.py プロジェクト: AdUser/karesansui
    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
コード例 #21
0
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        bridge_prefix = {
            "XEN": "xenbr",
            "KVM": "br|bondbr",
            #"KVM":"eth|bondbr",
        }

        model = findbyguest1(self.orm, guest_id)

        # virt
        self.kvc = KaresansuiVirtConnection()
        try:
            domname = self.kvc.uuid_to_domname(model.uniq_key)
            if not domname:
                return web.notfound()
            virt = self.kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            self.view.guest = guest

            # Output .input
            if self.is_mode_input() is True:
                try:
                    VMType = guest.info["virt"].get_info()["VMType"].upper()
                except:
                    VMType = "KVM"

                self.view.VMType = VMType

                # Network
                phydev = []
                phydev_regex = re.compile(r"%s" % bridge_prefix[VMType])

                for dev, dev_info in get_ifconfig_info().iteritems():
                    try:
                        if phydev_regex.match(dev):
                            phydev.append(dev)
                    except:
                        pass
                if len(phydev) == 0:
                    phydev.append("%s0" % bridge_prefix[VMType])

                phydev.sort()
                self.view.phydev = phydev  # Physical device
                self.view.virnet = sorted(
                    self.kvc.list_active_network())  # Virtual device
                self.view.mac_address = generate_mac_address(
                )  # new mac address

                # Disk
                inactive_pool = []
                active_pool = self.kvc.list_active_storage_pool()
                pools = inactive_pool + active_pool
                pools.sort()

                if not pools:
                    return web.badrequest('One can not start a storage pool.')

                pools_info = {}
                pools_vols_info = {}
                pools_iscsi_blocks = {}
                already_vols = []
                guests = []

                guests += self.kvc.list_inactive_guest()
                guests += self.kvc.list_active_guest()
                for guest in guests:
                    already_vol = self.kvc.get_storage_volume_bydomain(
                        domain=guest, image_type=None, attr='path')
                    if already_vol:
                        already_vols += already_vol.keys()

                for pool in pools:
                    pool_obj = self.kvc.search_kvn_storage_pools(pool)[0]
                    if pool_obj.is_active() is True:
                        pools_info[pool] = pool_obj.get_info()

                        blocks = None
                        if pools_info[pool]['type'] == 'iscsi':
                            blocks = self.kvc.get_storage_volume_iscsi_block_bypool(
                                pool)
                            if blocks:
                                pools_iscsi_blocks[pool] = []
                        vols_obj = pool_obj.search_kvn_storage_volumes(
                            self.kvc)
                        vols_info = {}

                        for vol_obj in vols_obj:
                            vol_name = vol_obj.get_storage_volume_name()
                            vols_info[vol_name] = vol_obj.get_info()
                            if blocks:
                                if vol_name in blocks and vol_name not in already_vols:
                                    pools_iscsi_blocks[pool].append(
                                        vol_obj.get_info())

                        pools_vols_info[pool] = vols_info

                self.view.pools = pools
                self.view.pools_info = pools_info
                self.view.pools_vols_info = pools_vols_info
                self.view.pools_iscsi_blocks = pools_iscsi_blocks

                if VMType == "KVM":
                    self.view.DISK_FORMATS = DISK_QEMU_FORMAT
                else:
                    self.view.DISK_FORMATS = DISK_NON_QEMU_FORMAT

                self.view.bus_types = self.kvc.bus_types

            else:  # .part
                self.view.ifinfo = virt.get_interface_info()  # interface info
                self.view.disk_info = virt.get_disk_info()  # Disk info

        finally:
            self.kvc.close()

        return True
コード例 #22
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        if self.is_mode_input() is True:
            self.view.plugins = WATCH_PLUGINS
            self.view.cpu_type_instance = COLLECTD_CPU_TYPE_INSTANCE
            self.view.memory_type_instance = COLLECTD_MEMORY_TYPE_INSTANCE
            self.view.df_ds = COLLECTD_DF_DS
            self.view.interface_type = COLLECTD_INTERFACE_TYPE
            self.view.interface_ds = COLLECTD_INTERFACE_DS
            self.view.load_ds = COLLECTD_LOAD_DS

            cpu_logical_number = len(get_proc_cpuinfo())
            self.view.cpu_logical_number = range(1, cpu_logical_number + 1)
            self.view.memory_size = string.atol(
                get_proc_meminfo()["MemTotal"][0]) / 1024
            self.view.df_list = get_fs_info()
            self.view.interface_list = get_ifconfig_info().keys()

            ## guest os list
            from karesansui.lib.utils import get_dom_list
            from karesansui.lib.virt.virt import KaresansuiVirtConnection
            from karesansui.lib.merge import MergeGuest
            self.view.dom_list = get_dom_list()

            dom_info = {}
            for domname in get_dom_list():
                kvc = KaresansuiVirtConnection()
                virt = kvc.search_kvg_guests(domname)[0]
                dom_info[domname] = {}
                dom_info[domname]['network'] = []
                dom_info[domname]['disk'] = []
                dom_info[domname]['disk_size'] = {}
                for net_dev in virt.get_interface_info():
                    dom_info[domname]['network'].append(
                        net_dev['target']['dev'])
                for disk in virt.get_disk_info():
                    dom_info[domname]['disk'].append(disk['target']['dev'])
                    dom_info[domname]['disk_size'][
                        disk['target']['dev']] = disk['source']['size']

                dom_info[domname]['vcpu'] = virt.get_vcpus_info()['max_vcpus']
                kvc.close()
            self.view.dom_info = dom_info

            ## disk info
            self.view.disk_size_info = {}
            for disk_data in get_fs_info():
                self.view.disk_size_info[
                    disk_data['Filesystem']] = disk_data['1048576-blocks']

            self.view.processer_num = len(get_proc_cpuinfo().keys())
            self.view.supported_langs = DEFAULT_LANGS.keys()
            self.view.myaddress = self.me.email
            self.view.mta = "%s:%s" % (
                karesansui.config['application.mail.server'],
                karesansui.config['application.mail.port'])
            self.view.alert_trigger_count = DEFAULT_ALERT_TRIGGER_COUNT
            self.view.slient_period = DEFAULT_SLIENT_PERIOD
            return True

        if not validates_query(self):
            self.logger.debug("Show watch is failed, "
                              "Invalid query value "
                              "- query=%s" % self.input.q)
            return web.badrequest(self.view.alert)

        if not validates_page(self):
            self.logger.debug("Show watch is failed, "
                              "Invalid page value - page=%s" % self.input.p)
            return web.badrequest(self.view.alert)

        if is_param(self.input, 'q') is True:
            watchs = w_findbyname_or_plugin(self.orm, self.input.q)
            if not watchs:
                self.logger.debug("Show watch is failed, "
                                  "Could not find watch "
                                  "- query=%s" % self.input.q)
                return web.nocontent()
            self.view.search_value = self.input.q
        else:
            watchs = w_findbyall(self.orm)
            self.view.search_value = ""

        if is_param(self.input, 'p') is True:
            start = int(self.input.p)
        else:
            start = 0

        pager = Pager(watchs, start, WATCH_LIST_RANGE)
        if not pager.exist_now_page() and is_param(self.input, 'p') is True:
            self.logger.debug("Show watch is failed, "
                              "Could not find page - page=%s" % self.input.p)
            return web.nocontent()

        self.view.pager = pager
        self.view.input = self.input

        return True
コード例 #23
0
ファイル: hostby1watch.py プロジェクト: AdUser/karesansui
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        if self.is_mode_input() is True:
            self.view.plugins = WATCH_PLUGINS
            self.view.cpu_type_instance = COLLECTD_CPU_TYPE_INSTANCE
            self.view.memory_type_instance = COLLECTD_MEMORY_TYPE_INSTANCE
            self.view.df_ds = COLLECTD_DF_DS
            self.view.interface_type = COLLECTD_INTERFACE_TYPE
            self.view.interface_ds = COLLECTD_INTERFACE_DS
            self.view.load_ds = COLLECTD_LOAD_DS

            cpu_logical_number = len(get_proc_cpuinfo())
            self.view.cpu_logical_number = range(1, cpu_logical_number+1)
            self.view.memory_size = string.atol(get_proc_meminfo()["MemTotal"][0]) / 1024
            self.view.df_list = get_fs_info()
            self.view.interface_list = get_ifconfig_info().keys()

            ## guest os list
            from karesansui.lib.utils import get_dom_list
            from karesansui.lib.virt.virt import KaresansuiVirtConnection
            from karesansui.lib.merge import MergeGuest
            self.view.dom_list = get_dom_list()

            dom_info = {}
            for domname in get_dom_list():
                kvc = KaresansuiVirtConnection()
                virt = kvc.search_kvg_guests(domname)[0]
                dom_info[domname] = {}
                dom_info[domname]['network'] = []
                dom_info[domname]['disk'] = []
                dom_info[domname]['disk_size'] = {}
                for net_dev in virt.get_interface_info():
                    dom_info[domname]['network'].append(net_dev['target']['dev'])
                for disk in virt.get_disk_info():
                    dom_info[domname]['disk'].append(disk['target']['dev'])
                    dom_info[domname]['disk_size'][disk['target']['dev']] = disk['source']['size']

                dom_info[domname]['vcpu'] = virt.get_vcpus_info()['max_vcpus']
                kvc.close()
            self.view.dom_info = dom_info

            ## disk info 
            self.view.disk_size_info = {}
            for disk_data in get_fs_info():
                self.view.disk_size_info[disk_data['Filesystem']] = disk_data['1048576-blocks']

            self.view.processer_num = len(get_proc_cpuinfo().keys())
            self.view.supported_langs = DEFAULT_LANGS.keys()
            self.view.myaddress = self.me.email
            self.view.mta = "%s:%s" % (karesansui.config['application.mail.server'],
                                       karesansui.config['application.mail.port'])
            self.view.alert_trigger_count = DEFAULT_ALERT_TRIGGER_COUNT;
            self.view.slient_period = DEFAULT_SLIENT_PERIOD;
            return True

        if not validates_query(self):
            self.logger.debug("Show watch is failed, "
                              "Invalid query value "
                              "- query=%s" % self.input.q)
            return web.badrequest(self.view.alert)

        if not validates_page(self):
            self.logger.debug("Show watch is failed, "
                              "Invalid page value - page=%s" % self.input.p)
            return web.badrequest(self.view.alert)

        if is_param(self.input, 'q') is True:
            watchs = w_findbyname_or_plugin(self.orm, self.input.q)
            if not watchs:
                self.logger.debug("Show watch is failed, "
                                  "Could not find watch "
                                  "- query=%s" % self.input.q)
                return web.nocontent()
            self.view.search_value = self.input.q
        else:
            watchs = w_findbyall(self.orm)
            self.view.search_value = ""

        if is_param(self.input, 'p') is True:
            start = int(self.input.p)
        else:
            start = 0

        pager = Pager(watchs, start, WATCH_LIST_RANGE)
        if not pager.exist_now_page() and is_param(self.input, 'p') is True:
            self.logger.debug("Show watch is failed, "
                              "Could not find page - page=%s" % self.input.p)
            return web.nocontent()

        self.view.pager = pager
        self.view.input = self.input

        return True
コード例 #24
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)
        uris = available_virt_uris()

        #import pdb; pdb.set_trace()
        if model.attribute == MACHINE_ATTRIBUTE["URI"]:
            uri_guests = []
            uri_guests_status = {}
            uri_guests_kvg = {}
            uri_guests_info = {}
            uri_guests_name = {}
            segs = uri_split(model.hostname)
            uri = uri_join(segs, without_auth=True)
            creds = ''
            if segs["user"] is not None:
                creds += segs["user"]
                if segs["passwd"] is not None:
                    creds += ':' + segs["passwd"]

            # Output .part
            if self.is_mode_input() is not True:
                try:
                    self.kvc = KaresansuiVirtConnectionAuth(uri, creds)
                    host = MergeHost(self.kvc, model)
                    for guest in host.guests:

                        _virt = self.kvc.search_kvg_guests(
                            guest.info["model"].name)
                        if 0 < len(_virt):
                            for _v in _virt:
                                uuid = _v.get_info()["uuid"]
                                uri_guests_info[uuid] = guest.info
                                uri_guests_kvg[uuid] = _v
                                uri_guests_name[uuid] = guest.info[
                                    "model"].name.encode("utf8")

                    for name in sorted(uri_guests_name.values(),
                                       key=str.lower):
                        for uuid in dict_search(name, uri_guests_name):
                            uri_guests.append(
                                MergeGuest(uri_guests_info[uuid]["model"],
                                           uri_guests_kvg[uuid]))
                            uri_guests_status[uuid] = uri_guests_info[uuid][
                                'virt'].status()

                finally:
                    self.kvc.close()

                # .json
                if self.is_json() is True:
                    guests_json = []
                    for x in uri_guests:
                        guests_json.append(x.get_json(self.me.languages))

                    self.view.uri_guests = json_dumps(guests_json)
                else:
                    self.view.uri_guests = uri_guests
                    self.view.uri_guests_status = uri_guests_status

        self.kvc = KaresansuiVirtConnection()
        try:  # libvirt connection scope -->

            # Storage Pool
            #inactive_pool = self.kvc.list_inactive_storage_pool()
            inactive_pool = []
            active_pool = self.kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            if not pools:
                return web.badrequest('One can not start a storage pool.')

            # Output .input
            if self.is_mode_input() is True:
                self.view.pools = pools
                pools_info = {}
                pools_vols_info = {}
                pools_iscsi_blocks = {}
                already_vols = []
                guests = []

                guests += self.kvc.list_inactive_guest()
                guests += self.kvc.list_active_guest()
                for guest in guests:
                    already_vol = self.kvc.get_storage_volume_bydomain(
                        domain=guest, image_type=None, attr='path')
                    if already_vol:
                        already_vols += already_vol.keys()

                for pool in pools:
                    pool_obj = self.kvc.search_kvn_storage_pools(pool)[0]
                    if pool_obj.is_active() is True:
                        pools_info[pool] = pool_obj.get_info()

                        blocks = None
                        if pools_info[pool]['type'] == 'iscsi':
                            blocks = self.kvc.get_storage_volume_iscsi_block_bypool(
                                pool)
                            if blocks:
                                pools_iscsi_blocks[pool] = []
                        vols_obj = pool_obj.search_kvn_storage_volumes(
                            self.kvc)
                        vols_info = {}

                        for vol_obj in vols_obj:
                            vol_name = vol_obj.get_storage_volume_name()
                            vols_info[vol_name] = vol_obj.get_info()
                            if blocks:
                                if vol_name in blocks and vol_name not in already_vols:
                                    pools_iscsi_blocks[pool].append(
                                        vol_obj.get_info())

                        pools_vols_info[pool] = vols_info

                self.view.pools_info = pools_info
                self.view.pools_vols_info = pools_vols_info
                self.view.pools_iscsi_blocks = pools_iscsi_blocks

                bridge_prefix = {
                    "XEN": "xenbr",
                    "KVM": KVM_BRIDGE_PREFIX,
                }
                self.view.host_id = host_id
                self.view.DEFAULT_KEYMAP = DEFAULT_KEYMAP
                self.view.DISK_NON_QEMU_FORMAT = DISK_NON_QEMU_FORMAT
                self.view.DISK_QEMU_FORMAT = DISK_QEMU_FORMAT

                self.view.hypervisors = {}
                self.view.mac_address = {}
                self.view.keymaps = {}
                self.view.phydev = {}
                self.view.virnet = {}

                used_ports = {}

                for k, v in MACHINE_HYPERVISOR.iteritems():
                    if k in available_virt_mechs():
                        self.view.hypervisors[k] = v
                        uri = uris[k]
                        mem_info = self.kvc.get_mem_info()
                        active_networks = self.kvc.list_active_network()
                        used_graphics_ports = self.kvc.list_used_graphics_port(
                        )
                        bus_types = self.kvc.bus_types
                        self.view.bus_types = bus_types
                        self.view.max_mem = mem_info['host_max_mem']
                        self.view.free_mem = mem_info['host_free_mem']
                        self.view.alloc_mem = mem_info['guest_alloc_mem']

                        self.view.mac_address[k] = generate_mac_address(k)
                        self.view.keymaps[k] = eval(
                            "get_keymaps(%s_KEYMAP_DIR)" % k)

                        # Physical device
                        phydev = []
                        phydev_regex = re.compile(r"%s" % bridge_prefix[k])
                        for dev, dev_info in get_ifconfig_info().iteritems():
                            try:
                                if phydev_regex.match(dev):
                                    phydev.append(dev)
                            except:
                                pass
                        if len(phydev) == 0:
                            phydev.append("%s0" % bridge_prefix[k])
                        phydev.sort()
                        self.view.phydev[k] = phydev  # Physical device

                        # Virtual device
                        self.view.virnet[k] = sorted(active_networks)
                        used_ports[k] = used_graphics_ports

                exclude_ports = []
                for k, _used_port in used_ports.iteritems():
                    exclude_ports = exclude_ports + _used_port
                    exclude_ports = sorted(exclude_ports)
                    exclude_ports = [
                        p for p, q in zip(exclude_ports, exclude_ports[1:] +
                                          [None]) if p != q
                    ]
                self.view.graphics_port = next_number(GRAPHICS_PORT_MIN_NUMBER,
                                                      PORT_MAX_NUMBER,
                                                      exclude_ports)

            else:  # .part
                models = findbyhost1guestall(self.orm, host_id)
                guests = []
                if models:
                    # Physical Guest Info
                    self.view.hypervisors = {}
                    for model in models:
                        for k, v in MACHINE_HYPERVISOR.iteritems():
                            if k in available_virt_mechs():
                                self.view.hypervisors[k] = v
                                uri = uris[k]
                                if hasattr(self, "kvc") is not True:
                                    self.kvc = KaresansuiVirtConnection(uri)
                                domname = self.kvc.uuid_to_domname(
                                    model.uniq_key)
                                #if not domname: return web.conflict(web.ctx.path)
                                _virt = self.kvc.search_kvg_guests(domname)
                                if 0 < len(_virt):
                                    guests.append(MergeGuest(model, _virt[0]))
                                else:
                                    guests.append(MergeGuest(model, None))

                # Exported Guest Info
                exports = {}
                for pool_name in pools:
                    files = []

                    pool = self.kvc.search_kvn_storage_pools(pool_name)
                    path = pool[0].get_info()["target"]["path"]

                    if os.path.exists(path):
                        for _afile in glob.glob("%s/*/info.dat" % (path, )):
                            param = ExportConfigParam()
                            param.load_xml_config(_afile)

                            _dir = os.path.dirname(_afile)

                            uuid = param.get_uuid()
                            name = param.get_domain()
                            created = param.get_created()
                            title = param.get_title()
                            if title != "":
                                title = re.sub("[\r\n]", "", title)
                            if title == "":
                                title = _('untitled')

                            if created != "":
                                created_str = time.strftime("%Y/%m/%d %H:%M:%S", \
                                                            time.localtime(float(created)))
                            else:
                                created_str = _("N/A")

                            files.append({
                                "dir": _dir,
                                "pool": pool_name,
                                #"b64dir" : base64_encode(_dir),
                                "uuid": uuid,
                                "name": name,
                                "created": int(created),
                                "created_str": created_str,
                                "title": title,
                                "icon": param.get_database()["icon"],
                            })

                    exports[pool_name] = files

                # .json
                if self.is_json() is True:
                    guests_json = []
                    for x in guests:
                        guests_json.append(x.get_json(self.me.languages))

                    self.view.guests = json_dumps(guests_json)
                else:
                    self.view.exports = exports
                    self.view.guests = guests

            return True
        except:
            pass
        finally:
            #self.kvc.close()
            pass  # libvirt connection scope --> Guest#_post()
コード例 #25
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        rule_id = param[1]
        if not validates_param_id(self, rule_id):
            return web.notfound(self.view.alert)

        kit = KaresansuiIpTables()
        kit.firewall_xml = kit.read_firewall_xml()

        rules = kit.get_rules()
        cnt = 1
        for rule in rules:
            if cnt == int(rule_id):
                self.view.rule = rule
                break
            cnt = cnt + 1

        if self.is_mode_input():
            self.view.targets = kit.basic_targets['filter']
            self.view.protocols = kit.chain_protos
            self.view.netinfo = get_ifconfig_info()
            devtype_regexs = {
                "phy":"^(lo|eth)",
                "vir":"^(xenbr|virbr|vif|veth)",
                }
            devtype_phy_regex = re.compile(r"%s" % devtype_regexs['phy'])
            devtype_vir_regex = re.compile(r"%s" % devtype_regexs['vir'])

            devs = {}
            devs['phy'] = []
            devs['vir'] = []
            devs['oth'] = []
            cidrs = []
            ips = []
            for dev,dev_info in get_ifconfig_info().iteritems():
                try:
                    if devtype_phy_regex.match(dev):
                        devs['phy'].append(dev)
                    elif devtype_vir_regex.match(dev):
                        devs['vir'].append(dev)
                    else:
                        devs['oth'].append(dev)
                    if dev_info['ipaddr'] is not None:
                        if not dev_info['ipaddr'] in ips:
                            ips.append(dev_info['ipaddr'])
                    if dev_info['cidr'] is not None:
                        if not dev_info['cidr'] in cidrs:
                            cidrs.append(dev_info['cidr'])
                except:
                    pass
            devs['phy'].sort()
            devs['vir'].sort()
            devs['oth'].sort()
            self.view.devs = [{'Physical' : devs['phy']},
                              {'Virtual' : devs['vir']},
                              {'Other' : devs['oth']},
                              ]
            self.view.cidrs = cidrs
            self.view.ips = ips
            return True
        else:
            return web.nomethod()
コード例 #26
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()
        self.view.host_id = host_id

        target = param[1]
        if target is None: return web.notfound()
        self.view.target = target

        group_display = False
        dev_list = []
        graph_type = []
        rrd = RRD()
        if target == "cpu":
            for dev in range(0, len(get_proc_cpuinfo())):
                if rrd.check_rrd_file_exist("cpu", dev):
                    dev_list.append(dev)
            graph_type = ['default']
        elif target == "memory":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "df":
            df_list = get_fs_info()
            for fs in df_list:
                if COLLECTD_DF_RRPORT_BY_DEVICE is True:
                    dev = fs['Filesystem']
                    dev = re.sub(r'^/dev/', '', dev)
                    dev = re.sub(r'/', '_', dev)
                else:
                    dev = fs['Mounted']
                    if dev == "/":
                        dev = "root"
                    else:
                        dev = re.sub(r'^/', '', dev)
                        dev = re.sub(r'/', '_', dev)
                if rrd.check_rrd_file_exist("df", dev):
                    dev_list.append(dev)
            graph_type = ['default']

        elif target == "disk":
            group_display = True
            disk_list = get_hdd_list()
            for disk in disk_list:
                dev = disk
                dev = re.sub(r'^/dev/', '', dev)
                if rrd.check_rrd_file_exist("disk", dev):
                    dev_list.append(dev)
            graph_type = ['merged', 'octets', 'ops', 'time']

        elif target == "interface":
            group_display = True
            if_list = get_ifconfig_info().keys()
            for dev in if_list:
                if rrd.check_rrd_file_exist("interface", dev):
                    dev_list.append(dev)
            graph_type = ['packets', 'octets', 'errors']

        elif target == "load":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "uptime":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "users":
            dev_list = ['default']
            graph_type = ['default']
        elif target == "libvirt":
            virt_cpu_type = ['default']
            virt_disk_type = ['octets', 'ops']
            virt_interface_type = ['packets', 'octets', 'errors', 'dropped']
            virt_list = {}
            virt_file_exist = {}

            try:
                kvc = KaresansuiVirtConnection()

                for domname in get_dom_list():
                    virt_list[domname] = {}

                    if rrd.set_rrd_dir_host(domname) is False:
                        virt_file_exist[domname] = False
                        continue

                    try:
                        virt = kvc.search_kvg_guests(domname)[0]
                    except:
                        virt_file_exist[domname] = False
                        continue

                    virt_list[domname]['vcpu'] = {}
                    if rrd.check_rrd_file_exist("libvirt", "total", "vcpu"):
                        virt_list[domname]['vcpu']['total'] = virt_cpu_type
                    for i in range(virt.get_vcpus_info()['max_vcpus']):
                        if rrd.check_rrd_file_exist("libvirt", i, "vcpu"):
                            virt_list[domname]['vcpu'][i] = virt_cpu_type

                    virt_list[domname]['disk'] = {}
                    for disk in virt.get_disk_info():
                        if rrd.check_rrd_file_exist("libvirt",
                                                    disk['target']['dev'],
                                                    "disk"):
                            virt_list[domname]['disk'][
                                disk['target']['dev']] = virt_disk_type

                    virt_list[domname]['interface'] = {}
                    for net_dev in virt.get_interface_info():
                        if rrd.check_rrd_file_exist("libvirt",
                                                    net_dev['target']['dev'],
                                                    "interface"):
                            virt_list[domname]['interface'][
                                net_dev['target']['dev']] = virt_interface_type

                    if virt_list[domname]['vcpu'] == {} and \
                            virt_list[domname]['disk'] == {} and \
                            virt_list[domname]['interface'] == {}:
                        virt_list[domname] = {}
                        virt_file_exist[domname] = False
                    else:
                        virt_file_exist[domname] = True

            finally:
                kvc.close()

            self.view.virt_list = virt_list
            self.view.virt_file_exist = virt_file_exist

        self.view.group_display = group_display
        dev_list.sort()
        self.view.dev_list = dev_list
        self.view.graph_type = graph_type

        return True
コード例 #27
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        self.view.current = get_ifconfig_info()
        self.view.device = param[1]

        modules = ["ifcfg"]

        host = findbyhost1(self.orm, host_id)
        dop = read_conf(modules,self,host)
        if dop is False:
            self.logger.error("Get nic info failed. Failed read conf.")
            return web.internalerror('Internal Server Error. (Read conf)')

        self.view.bootproto = dop.get("ifcfg",[self.view.device,"BOOTPROTO"])
        if self.view.bootproto is False:
            self.view.bootproto = "static"

        self.view.onboot    = dop.get("ifcfg",[self.view.device,"ONBOOT"])
        if self.view.onboot is False:
            self.view.onboot = "yes"

        self.view.ipaddr    = dop.get("ifcfg",[self.view.device,"IPADDR"])
        if self.view.ipaddr is False:
            self.view.ipaddr = ""

        self.view.netmask   = dop.get("ifcfg",[self.view.device,"NETMASK"])
        if self.view.netmask is False:
            self.view.netmask = ""

        self.view.network   = dop.get("ifcfg",[self.view.device,"NETWORK"])
        if self.view.network is False:
            net = NetworkAddress("%s/%s" % (self.view.ipaddr,self.view.netmask))
            if net.valid_addr(self.view.ipaddr) is True and net.valid_addr(self.view.netmask) is True:
                self.view.network = net.network
            else:
                self.view.network = ""

        self.view.broadcast = dop.get("ifcfg",[self.view.device,"BROADCAST"])
        if self.view.broadcast is False:
            net = NetworkAddress("%s/%s" % (self.view.ipaddr,self.view.netmask))
            if net.valid_addr(self.view.ipaddr) is True and net.valid_addr(self.view.netmask) is True:
                self.view.broadcast = net.broadcast
            else:
                self.view.broadcast = ""

        self.view.master    = dop.get("ifcfg",[self.view.device,"MASTER"])
        if self.view.master is False:
            self.view.master = ""

        self.view.c_ipaddr    = self.view.current[self.view.device]["ipaddr"]
        if self.view.c_ipaddr is None:
            self.view.c_ipaddr = ""

        self.view.c_netmask   = self.view.current[self.view.device]["mask"]
        if self.view.c_netmask is None:
            self.view.c_netmask = ""

        if self.view.current[self.view.device]["cidr"] is None:
            self.view.c_network = ""
        else:
            self.view.c_network = re.sub("\/.*","",self.view.current[self.view.device]["cidr"])

        self.view.c_broadcast = self.view.current[self.view.device]["bcast"]
        if self.view.c_broadcast is None:
            net = NetworkAddress("%s/%s" % (self.view.c_ipaddr,self.view.c_netmask))
            if net.valid_addr(self.view.c_ipaddr) is True and net.valid_addr(self.view.c_netmask) is True:
                self.view.c_broadcast = net.broadcast
            else:
                self.view.c_broadcast = ""

        self.view.c_hwaddr = self.view.current[self.view.device]["hwaddr"]
        if self.view.c_hwaddr is None:
            self.view.c_hwaddr = ""

        self.view.bond_info = get_bonding_info()

        self.view.c_master = ""
        for bond in self.view.bond_info:
            for slave in self.view.bond_info[bond]['slave']:
                if self.view.device == slave:
                    self.view.c_master = bond

        return True
コード例 #28
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        self.view.current = get_ifconfig_info()
        self.view.device = param[1]

        modules = ["ifcfg"]

        host = findbyhost1(self.orm, host_id)
        dop = read_conf(modules, self, host)
        if dop is False:
            self.logger.error("Get nic info failed. Failed read conf.")
            return web.internalerror('Internal Server Error. (Read conf)')

        self.view.bootproto = dop.get("ifcfg", [self.view.device, "BOOTPROTO"])
        if self.view.bootproto is False:
            self.view.bootproto = "static"

        self.view.onboot = dop.get("ifcfg", [self.view.device, "ONBOOT"])
        if self.view.onboot is False:
            self.view.onboot = "yes"

        self.view.ipaddr = dop.get("ifcfg", [self.view.device, "IPADDR"])
        if self.view.ipaddr is False:
            self.view.ipaddr = ""

        self.view.netmask = dop.get("ifcfg", [self.view.device, "NETMASK"])
        if self.view.netmask is False:
            self.view.netmask = ""

        self.view.network = dop.get("ifcfg", [self.view.device, "NETWORK"])
        if self.view.network is False:
            net = NetworkAddress("%s/%s" %
                                 (self.view.ipaddr, self.view.netmask))
            if net.valid_addr(self.view.ipaddr) is True and net.valid_addr(
                    self.view.netmask) is True:
                self.view.network = net.network
            else:
                self.view.network = ""

        self.view.broadcast = dop.get("ifcfg", [self.view.device, "BROADCAST"])
        if self.view.broadcast is False:
            net = NetworkAddress("%s/%s" %
                                 (self.view.ipaddr, self.view.netmask))
            if net.valid_addr(self.view.ipaddr) is True and net.valid_addr(
                    self.view.netmask) is True:
                self.view.broadcast = net.broadcast
            else:
                self.view.broadcast = ""

        self.view.master = dop.get("ifcfg", [self.view.device, "MASTER"])
        if self.view.master is False:
            self.view.master = ""

        self.view.c_ipaddr = self.view.current[self.view.device]["ipaddr"]
        if self.view.c_ipaddr is None:
            self.view.c_ipaddr = ""

        self.view.c_netmask = self.view.current[self.view.device]["mask"]
        if self.view.c_netmask is None:
            self.view.c_netmask = ""

        if self.view.current[self.view.device]["cidr"] is None:
            self.view.c_network = ""
        else:
            self.view.c_network = re.sub(
                "\/.*", "", self.view.current[self.view.device]["cidr"])

        self.view.c_broadcast = self.view.current[self.view.device]["bcast"]
        if self.view.c_broadcast is None:
            net = NetworkAddress("%s/%s" %
                                 (self.view.c_ipaddr, self.view.c_netmask))
            if net.valid_addr(self.view.c_ipaddr) is True and net.valid_addr(
                    self.view.c_netmask) is True:
                self.view.c_broadcast = net.broadcast
            else:
                self.view.c_broadcast = ""

        self.view.c_hwaddr = self.view.current[self.view.device]["hwaddr"]
        if self.view.c_hwaddr is None:
            self.view.c_hwaddr = ""

        self.view.bond_info = get_bonding_info()

        self.view.c_master = ""
        for bond in self.view.bond_info:
            for slave in self.view.bond_info[bond]['slave']:
                if self.view.device == slave:
                    self.view.c_master = bond

        return True