Exemple #1
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()
        if model.attribute == 0 and model.hypervisor == 1:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == 2:
            uri = uris["KVM"]
        else:
            uri = None

        # if input mode then return empty form
        if self.is_mode_input():
            self.view.host_id = host_id
            self.view.network = dict(name='', cidr='',
                                     dhcp_start='', dhcp_end='',
                                     forward_dev='', forward_mode='',
                                     bridge='')
            return True
        else:
            kvc = KaresansuiVirtConnection(uri)
            try:
                labelfunc = (('active', kvc.list_active_network),
                             ('inactive', kvc.list_inactive_network),
                             )
                # networks = {'active': [], 'inactive': []}
                networks = []
                for label, func in labelfunc:
                    for name in func():
                        try:
                            network = kvc.search_kvn_networks(name)[0] # throws KaresansuiVirtException
                            info = network.get_info()
                            # networks[label].append(info)
                            if info['is_active']:
                                info['activity'] = 'Active'
                            else:
                                info['activity'] = 'Inactive'
                            networks.append(info)
                        except KaresansuiVirtException, e:
                            # network not found
                            pass
            finally:
                kvc.close()

            self.view.networks = networks
            return True
Exemple #2
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()
        if model.attribute == 0 and model.hypervisor == 1:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == 2:
            uri = uris["KVM"]
        else:
            uri = None

        # if input mode then return empty form
        if self.is_mode_input():
            self.view.host_id = host_id
            self.view.network = dict(name='', cidr='',
                                     dhcp_start='', dhcp_end='',
                                     forward_dev='', forward_mode='',
                                     bridge='')
            return True
        else:
            kvc = KaresansuiVirtConnection(uri)
            try:
                labelfunc = (('active', kvc.list_active_network),
                             ('inactive', kvc.list_inactive_network),
                             )
                # networks = {'active': [], 'inactive': []}
                networks = []
                for label, func in labelfunc:
                    for name in func():
                        try:
                            network = kvc.search_kvn_networks(name)[0] # throws KaresansuiVirtException
                            info = network.get_info()
                            # networks[label].append(info)
                            if info['is_active']:
                                info['activity'] = 'Active'
                            else:
                                info['activity'] = 'Inactive'
                            networks.append(info)
                        except KaresansuiVirtException, e:
                            # network not found
                            pass
            finally:
                kvc.close()

            self.view.networks = networks
            return True
Exemple #3
0
    def _GET(self, *param, **params):
        models = findbyhostall(self.orm)
        uris = available_virt_uris()

        try:
            conf = env.get("KARESANSUI_CONF")
            _K2V = K2V(conf)
            config = _K2V.read()
        except (IOError, KaresansuiGadgetException):
            raise KaresansuiGadgetException

        self.view.application_uniqkey = config["application.uniqkey"]

        from karesansui.lib.file.configfile import LighttpdPortConf
        from karesansui.lib.const import LIGHTTPD_PORT_CONFIG

        try:
            conf_file = config["lighttpd.etc.dir"] + "/" + LIGHTTPD_PORT_CONFIG
            port_number = int(LighttpdPortConf(conf_file).read())
        except:
            port_number = 443

        try:
            hosts = []
            for model in models:
                if model.attribute == 0 and model.hypervisor == 1:
                    uri = uris["XEN"]
                elif model.attribute == 0 and model.hypervisor == 2:
                    uri = uris["KVM"]
                else:
                    uri = None
                self.kvc = KaresansuiVirtConnection(uri)
                host = MergeHost(self.kvc, model)
                host.info["model"].is_ssl = is_ssl(host.info["model"].hostname)
                # host.info['model'].is_ssl = is_ssl(host.info['model'].hostname,port_number)
                host.info["model"].port_number = port_number
                hosts.append(host)

            self.view.machines = hosts
        except KaresansuiVirtException:
            self.kvc.close()
            raise KaresansuiGadgetException

        return True
Exemple #4
0
    def _GET(self, *param, **params):
        models = findbyhostall(self.orm)
        uris = available_virt_uris()

        try:
            conf = env.get('KARESANSUI_CONF')
            _K2V = K2V(conf)
            config = _K2V.read()
        except (IOError, KaresansuiGadgetException):
            raise KaresansuiGadgetException

        self.view.application_uniqkey = config['application.uniqkey']

        port_number = 443

        try:
            hosts = []
            for model in models:
                if model.attribute == 0 and model.hypervisor == 1:
                    uri = uris["XEN"]
                elif model.attribute == 0 and model.hypervisor == 2:
                    uri = uris["KVM"]
                else:
                    uri = None
                self.kvc = KaresansuiVirtConnection(uri)
                host = MergeHost(self.kvc, model)
                host.info['model'].is_ssl = is_ssl(host.info['model'].hostname)
                #host.info['model'].is_ssl = is_ssl(host.info['model'].hostname,port_number)
                host.info['model'].port_number = port_number
                hosts.append(host)

            self.view.machines = hosts
        except KaresansuiVirtException:
            if hasattr(self, "kvc") is True:
                self.kvc.close()
            raise KaresansuiGadgetException

        return True
Exemple #5
0
    def _GET(self, *param, **params):
        models = findbyhostall(self.orm)
        uris = available_virt_uris()

        try:
            conf = env.get('KARESANSUI_CONF')
            _K2V = K2V(conf)
            config = _K2V.read()
        except (IOError, KaresansuiGadgetException):
            raise KaresansuiGadgetException

        self.view.application_uniqkey = config['application.uniqkey']

        port_number = 443

        try:
            hosts = []
            for model in models:
                if model.attribute == 0 and model.hypervisor == 1:
                    uri = uris["XEN"]
                elif model.attribute == 0 and model.hypervisor == 2:
                    uri = uris["KVM"]
                else:
                    uri = None
                self.kvc = KaresansuiVirtConnection(uri)
                host = MergeHost(self.kvc, model)
                host.info['model'].is_ssl = is_ssl(host.info['model'].hostname)
                #host.info['model'].is_ssl = is_ssl(host.info['model'].hostname,port_number)
                host.info['model'].port_number = port_number
                hosts.append(host)

            self.view.machines = hosts
        except KaresansuiVirtException:
            if hasattr(self, "kvc") is True:
                self.kvc.close()
            raise KaresansuiGadgetException

        return True
Exemple #6
0
    def _GET(self, *param, **params):

        if self.input.has_key('job_id') is True:
            self.view.job_id = self.input.job_id
        else:
            self.view.job_id = None

        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

        uris = available_virt_uris()
        if model.attribute == 0 and model.hypervisor == 1:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == 2:
            uri = uris["KVM"]
        else:
            uri = None

        # other_url
        other_url = "%s://%s%s/" % (
            self.view.ctx.protocol, model.hostname,
            karesansui.config['application.url.prefix'])

        if self.is_mode_input() is False:
            if karesansui.config["application.uniqkey"] == model.uniq_key:
                # My host
                host_cpuinfo = get_proc_cpuinfo()
                cpuinfo = {}
                cpuinfo["number"] = len(host_cpuinfo)
                cpuinfo["vendor"] = host_cpuinfo[0]["vendor_id"]
                cpuinfo["model"] = host_cpuinfo[0]["model name"]
                cpuinfo["frequency"] = host_cpuinfo[0]["cpu MHz"]

                host_meminfo = get_proc_meminfo()
                meminfo = {}
                meminfo["total"] = host_meminfo["MemTotal"][0]
                meminfo["free"] = host_meminfo["MemFree"][0]
                meminfo["buffers"] = host_meminfo["Buffers"][0]
                meminfo["cached"] = host_meminfo["Cached"][0]

                host_diskinfo = get_partition_info(VENDOR_DATA_DIR)
                diskinfo = {}
                diskinfo["total"] = host_diskinfo[1]
                diskinfo["free"] = host_diskinfo[3]

                self.kvc = KaresansuiVirtConnection(uri)
                try:
                    host = MergeHost(self.kvc, model)
                    if self.is_json() is True:
                        json_host = host.get_json(self.me.languages)
                        self.view.data = json_dumps({
                            "model": json_host["model"],
                            "cpuinfo": cpuinfo,
                            "meminfo": meminfo,
                            "diskinfo": diskinfo,
                        })
                    else:
                        self.view.model = host.info["model"]
                        self.view.virt = host.info["virt"]
                finally:
                    self.kvc.close()

            else:
                # other uri
                if model.attribute == 2:
                    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"]

                    try:
                        self.kvc = KaresansuiVirtConnectionAuth(uri, creds)

                        host = MergeHost(self.kvc, model)
                        if self.is_json() is True:
                            json_host = host.get_json(self.me.languages)
                            self.view.data = json_dumps({
                                "model":
                                json_host["model"],
                                "uri":
                                uri,
                                "num_of_guests":
                                len(host.guests),
                            })
                        else:
                            self.view.model = host.info["model"]
                            self.view.virt = host.info["virt"]
                            self.view.uri = uri
                            try:
                                self.view.auth_user = segs["user"]
                            except:
                                self.view.auth_user = ""
                            try:
                                self.view.auth_passwd = segs["passwd"]
                            except:
                                self.view.auth_passwd = ""

                    except:
                        pass

                    finally:
                        #if 'kvc' in dir(locals()["self"])
                        if 'kvc' in dir(self):
                            self.kvc.close()

                # other host
                else:
                    if self.is_json() is True:
                        self.view.data = json_dumps({
                            "model":
                            model.get_json(self.me.languages),
                            "other_url":
                            other_url,
                        })
                    else:
                        self.view.model = model
                        self.view.virt = None
                        self.view.other_url = other_url

            return True
        else:
            # mode=input
            if model.attribute == 2:
                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"]

                self.view.model = model
                self.view.uri = uri
                try:
                    self.view.auth_user = segs["user"]
                except:
                    self.view.auth_user = ""
                try:
                    self.view.auth_passwd = segs["passwd"]
                except:
                    self.view.auth_passwd = ""

            else:
                self.kvc = KaresansuiVirtConnection(uri)
                try:
                    host = MergeHost(self.kvc, model)
                    self.view.model = host.info["model"]
                finally:
                    self.kvc.close()

            self.view.application_uniqkey = karesansui.config[
                'application.uniqkey']

            return True
Exemple #7
0
    def _POST(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()
        if model.attribute == 0 and model.hypervisor == 1:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == 2:
            uri = uris["KVM"]
        else:
            uri = None

        if not validates_guest_add(self):
            return web.badrequest(self.view.alert)

        try:
            try:
                self.kvc = KaresansuiVirtConnection(uri)
                active_guests = self.kvc.list_active_guest()
                inactive_guests = self.kvc.list_inactive_guest()
                used_graphics_ports = self.kvc.list_used_graphics_port()
                used_mac_addrs = self.kvc.list_used_mac_addr()
                mem_info = self.kvc.get_mem_info()

                if is_param(self.input, "vm_mem_size"):
                    if mem_info['host_free_mem'] < int(self.input.vm_mem_size):
                        return web.badrequest(_("Space not enough to allocate guest memory."))

                if is_param(self.input, "pool_type") and \
                       self.input.pool_type != "block" and \
                       is_param(self.input, "pool_dir"):
                    target_path = self.kvc.get_storage_pool_targetpath(self.input.pool_dir)
                    if target_path: # disk
                        if not chk_create_disk(target_path, self.input.vm_disk_size):
                            partition = get_partition_info(target_path, header=False)
                            return web.badrequest(_("No space available to create disk image in '%s' partition.") % partition[5][0])
            except:
                raise
        finally:
            del self.kvc

        # Check on whether value has already been used
        # Guest OS
        if (self.input.domain_name in active_guests) \
               or (self.input.domain_name in inactive_guests):
            return web.conflict(web.ctx.path, "Guest OS is already there.")
        # Graphics Port Number
        if(int(self.input.vm_graphics_port) in used_graphics_ports):
            return web.conflict(web.ctx.path, "Graphics Port is already there.")
        # MAC Address
        if(self.input.vm_mac in used_mac_addrs):
            return web.conflict(web.ctx.path, "MAC Address is already there.")

        uuid = string_from_uuid(generate_uuid())

        options = {}
        options['uuid'] = uuid

        if is_param(self.input, "domain_name"):
            options['name'] = self.input.domain_name
        if is_param(self.input, "vm_mem_size"):
            options['mem-size'] = self.input.vm_mem_size
        if is_param(self.input, "vm_kernel"):
            options['kernel'] = self.input.vm_kernel
        if is_param(self.input, "vm_initrd"):
            options['initrd'] = self.input.vm_initrd
        if is_param(self.input, "vm_iso"):
            options['iso'] = self.input.vm_iso
        if is_param(self.input, "keymap"):
            options['keymap'] = self.input.keymap

        is_create = False
        if is_param(self.input, "pool_type"):
            if is_param(self.input, "bus_type"):
                options['bus'] = self.input.bus_type

            if self.input.pool_type == "dir" or self.input.pool_type == "fs": # create volume
                is_create = True
                options['disk-format'] = self.input.disk_format
                options["storage-pool"] = self.input.pool_dir
                options["storage-volume"] = options['name'] # default domain name
                options['disk-size'] = self.input.vm_disk_size

            elif self.input.pool_type == "block": # iscsi block device
                (iscsi_pool, iscsi_volume) = self.input.pool_dir.split("/", 2)
                options["storage-pool"] = iscsi_pool
                options["storage-volume"] = iscsi_volume
            else:
                return web.badrequest()
        else:
            return web.badrequest()

        if is_param(self.input, "vm_graphics_port"):
            options['graphics-port'] = self.input.vm_graphics_port
        if is_param(self.input, "vm_mac"):
            options['mac'] = self.input.vm_mac
        if is_param(self.input, "vm_extra"):
            options['extra'] = self.input.vm_extra
        if is_param(self.input, "nic_type"):
            if self.input.nic_type == "phydev":
                options['interface-format'] = "b:" + self.input.phydev
            elif self.input.nic_type == "virnet":
                options['interface-format'] = "n:" + self.input.virnet

        if int(self.input.m_hypervisor) == MACHINE_HYPERVISOR['XEN']:
            i_hypervisor = MACHINE_HYPERVISOR['XEN']
            options['type'] = u"XEN"
        elif int(self.input.m_hypervisor) == MACHINE_HYPERVISOR['KVM']:
            i_hypervisor = MACHINE_HYPERVISOR['KVM']
            options['type'] = u"KVM"
        else:
            return web.badrequest("This is not the hypervisor.")

        host = findbyhost1(self.orm, host_id)

        # notebook
        note_title = None
        if is_param(self.input, "note_title"):
            note_title = self.input.note_title

        note_value = None
        if is_param(self.input, "note_value"):
            note_value = self.input.note_value

        _notebook = n_new(note_title, note_value)

        # tags
        _tags = None
        if is_param(self.input, "tags"):
            _tags = []
            tag_array = comma_split(self.input.tags)
            tag_array = uniq_sort(tag_array)
            for x in tag_array:
                if t_count(self.orm, x) == 0:
                    _tags.append(t_new(x))
                else:
                    _tags.append(t_name(self.orm, x))

        # Icon
        icon_filename = None
        if is_param(self.input, "icon_filename", empty=True):
            icon_filename = self.input.icon_filename

        _guest = m_new(created_user=self.me,
                       modified_user=self.me,
                       uniq_key=uni_force(uuid),
                       name=self.input.m_name,
                       attribute=MACHINE_ATTRIBUTE['GUEST'],
                       hypervisor=i_hypervisor,
                       notebook=_notebook,
                       tags=_tags,
                       icon=icon_filename,
                       is_deleted=False,
                       parent=host,
                       )

        ret =  regist_guest(self,
                            _guest,
                            icon_filename,
                            VIRT_COMMAND_CREATE_GUEST,
                            options,
                            ('Create Guest', 'Create Guest'),
                            {"name": options['name'],
                             "pool" : options["storage-pool"],
                             "volume" : options["uuid"],
                             },
                            is_create,
                            )
        if ret is True:
            return web.accepted()
        else:
            return False
Exemple #8
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()

        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()
Exemple #9
0
    def _POST(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()
        if model.attribute == 0 and model.hypervisor == 1:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == 2:
            uri = uris["KVM"]
        else:
            uri = None

        if not validates_network(self):
            self.logger.debug("Network creation failed. Did not validate.")
            return web.badrequest(self.view.alert)

        name       = self.input.name
        cidr       = self.input.cidr
        dhcp_start = self.input.dhcp_start
        dhcp_end   = self.input.dhcp_end
        bridge     = self.input.bridge

        # We support only 'nat' for forward-mode.
        forward_mode = ''
        if is_param(self.input, 'forward_mode'):
            if self.input.forward_mode == 'nat':
                forward_mode = 'nat'

        try:
            autostart = self.input.autostart
        except:
            autostart = "no"

        # Check if the name is available (not already used).
        kvc = KaresansuiVirtConnection(uri)
        try:
            try:
                kvc.search_kvn_networks(name)
                self.logger.debug("Network name '%s' already used." % name)
                url = '%s/%s/%s.part' % (web.ctx.home, web.ctx.path, name)
                self.logger.debug("Returning url %s as Location." % url)
                return web.conflict(url)
            except KaresansuiVirtException, e:
                # OK
                pass
        finally:
            kvc.close()

        # spin off create job
        options = {'dhcp-start': dhcp_start,
                   'dhcp-end'  : dhcp_end,
                   'bridge-name'    : bridge,
                   'forward-mode'   : forward_mode,
                   'autostart' : autostart,
                  }

        self.logger.debug('spinning off network_create_job name=%s, cidr=%s, options=%s' % (name, cidr, options))
        host = findbyhost1(self.orm, host_id)
        #network_create_job(self, name, cidr, host, options)

        options['name'] = name
        options['cidr'] = cidr

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], VIRT_COMMAND_CREATE_NETWORK), options)

        #_jobgroup = JobGroup('Create network', karesansui.sheconf['env.uniqkey'])
        #_jobgroup.jobs.append(Job('Create network', 0, _cmd))
        # Job Registration
        _jobgroup = JobGroup('Create network: %s' % name, karesansui.sheconf['env.uniqkey'])
        _jobgroup.jobs.append(Job('Create network', 0, _cmd))
        _machine2jobgroup = m2j_new(machine=host,
                                    jobgroup_id=-1,
                                    uniq_key=karesansui.sheconf['env.uniqkey'],
                                    created_user=self.me,
                                    modified_user=self.me,
                                    )

        save_job_collaboration(self.orm,
                               self.pysilhouette.orm,
                               _machine2jobgroup,
                               _jobgroup,
                               )

        self.logger.debug('(Create network) Job group id==%s', _jobgroup.id)
        url = '%s/job/%s.part' % (web.ctx.home, _jobgroup.id)
        self.logger.debug('Returning Location: %s' % url)

        return web.accepted()
Exemple #10
0
    def _GET(self, *param, **params):

        if self.input.has_key('job_id') is True:
            self.view.job_id = self.input.job_id
        else:
            self.view.job_id = None

        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

        uris = available_virt_uris()
        if model.attribute == 0 and model.hypervisor == 1:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == 2:
            uri = uris["KVM"]
        else:
            uri = None

        # other_url
        other_url = "%s://%s%s/" % (self.view.ctx.protocol, model.hostname, karesansui.config['application.url.prefix'])
        
        if self.is_mode_input() is False:
            if karesansui.config["application.uniqkey"] == model.uniq_key:
                # My host
                host_cpuinfo = get_proc_cpuinfo()
                cpuinfo = {}
                cpuinfo["number"] = len(host_cpuinfo)
                cpuinfo["vendor"] = host_cpuinfo[0]["vendor_id"]
                cpuinfo["model"] = host_cpuinfo[0]["model name"]
                cpuinfo["frequency"] = host_cpuinfo[0]["cpu MHz"]

                host_meminfo = get_proc_meminfo()
                meminfo = {}
                meminfo["total"] = host_meminfo["MemTotal"][0]
                meminfo["free"] = host_meminfo["MemFree"][0]
                meminfo["buffers"] = host_meminfo["Buffers"][0]
                meminfo["cached"] = host_meminfo["Cached"][0]

                host_diskinfo = get_partition_info(VENDOR_DATA_DIR)
                diskinfo = {}
                diskinfo["total"] = host_diskinfo[1]
                diskinfo["free"] = host_diskinfo[3]

                self.kvc = KaresansuiVirtConnection(uri)
                try:
                    host = MergeHost(self.kvc, model)
                    if self.is_json() is True:
                        json_host = host.get_json(self.me.languages)
                        self.view.data = json_dumps({"model": json_host["model"], 
                                                     "cpuinfo": cpuinfo,
                                                     "meminfo": meminfo,
                                                     "diskinfo": diskinfo,
                                                     })
                    else:
                        self.view.model = host.info["model"]
                        self.view.virt = host.info["virt"]
                finally:
                    self.kvc.close()

            else:
                # other host
                if self.is_json() is True:
                    self.view.data = json_dumps({
                        "model": model.get_json(self.me.languages),
                        "other_url" : other_url,
                        })
                else:
                    self.view.model = model
                    self.view.virt = None
                    self.view.other_url = other_url

            return True
        else:
            # mode=input
            self.kvc = KaresansuiVirtConnection(uri)
            try:
                host = MergeHost(self.kvc, model)
                self.view.model = host.info["model"]
                self.view.application_uniqkey = karesansui.config['application.uniqkey']
            finally:
                self.kvc.close()

            return True
Exemple #11
0
    def process(self):
        (opts, args) = getopts()

        start_msg = _("Generated by %s on %s") % (prog_name,time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
        print "# " + start_msg

        if is_executable(COMMAND_VIRSH):
            old_lang = os.environ.get('LANG')
            os.environ['LANG'] = "C"

            if opts.all is True or (opts.list is not True and opts.netlist is not True and opts.nodeinfo is not True and opts.poollist is not True):
                """ Show version """
                print ""
                print "## Version"
                (rc,res) = execute_command([COMMAND_VIRSH,"version"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line
                self.showKaresansuiVersion()

            if opts.all is True:
                """ Show uri """
                print ""
                print "## URI"
                (rc,res) = execute_command([COMMAND_VIRSH,"uri"])
                if rc == 0:
                    print _("Connecting URI: %s") %(res[0])

                """ Show hostname """
                print ""
                print "## Hostname"
                (rc,res) = execute_command([COMMAND_VIRSH,"hostname"])
                if rc == 0:
                    print _("Hypervisor hostname: %s") %(res[0])

            if opts.all is True or opts.nodeinfo is True:
                """ Show nodeinfo """
                print ""
                print "## Node Information"
                (rc,res) = execute_command([COMMAND_VIRSH,"nodeinfo"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.list is True:
                """ Show dom list """
                print ""
                print "## Domain List"
                (rc,res) = execute_command([COMMAND_VIRSH,"list","--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.netlist is True:
                """ Show net list """
                print ""
                print "## Network List"
                (rc,res) = execute_command([COMMAND_VIRSH,"net-list","--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.poollist is True:
                """ Show pool list """
                print ""
                print "## Pool List"
                (rc,res) = execute_command([COMMAND_VIRSH,"pool-list","--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            os.environ['LANG'] = old_lang
        else:
            try:
                conn = libvirt.openReadOnly(None)
                hypervisor = conn.getType()

                if opts.all is True or (opts.list is not True and opts.netlist is not True and opts.nodeinfo is not True and opts.poollist is not True):
                    """ Show version """
                    print ""
                    print "## Version"
                    ret = libvirtmod.virGetVersion(hypervisor)
                    libVersion = ret[0]
                    apiVersion = ret[1]

                    libVersion_major = libVersion / 1000000
                    libVersion %= 1000000
                    libVersion_minor = libVersion / 1000
                    libVersion_rel = libVersion % 1000
                    apiVersion_major = apiVersion / 1000000
                    apiVersion %= 1000000
                    apiVersion_minor = apiVersion / 1000
                    apiVersion_rel = apiVersion % 1000

                    print _("Using library: libvir %d.%d.%d") %(libVersion_major, libVersion_minor, libVersion_rel)
                    print _("Using API: %s %d.%d.%d") %(hypervisor, apiVersion_major, apiVersion_minor, apiVersion_rel)

                    try:
                        # See https://www.redhat.com/archives/libvir-list/2010-January/msg00723.html
                        ret = libvirtmod.virConnectGetVersion(conn._o)
                        hvVersion = ret
                        hvVersion_major = hvVersion / 1000000
                        hvVersion %= 1000000
                        hvVersion_minor = hvVersion / 1000
                        hvVersion_rel = hvVersion % 1000
                        print _("Running hypervisor: %s %d.%d.%d") %(hypervisor, hvVersion_major, hvVersion_minor, hvVersion_rel)
                    except:
                        if hypervisor == "QEMU":
                            (rc,res) = execute_command(["qemu","--version"])
                            if rc == 0:
                                p = re.compile("QEMU PC emulator version ([0-9\.]+),.*")
                                if p.search(res[0]):
                                    qemuVersion = p.sub("\\1",res[0])
                                    print _("Running hypervisor: %s %s") %(hypervisor, qemuVersion)

                    self.showKaresansuiVersion()

                if opts.all is True:
                    """ Show uri """
                    print ""
                    print "## URI"
                    uri = conn.getURI()
                    print _("Connecting URI: %s") %(uri)

                    """ Show hostname """
                    print ""
                    print "## Hostname"
                    hostname = conn.getHostname()
                    print _("Hypervisor hostname: %s") %(hostname)

                if opts.all is True or opts.nodeinfo is True:
                    """ Show nodeinfo """
                    print ""
                    print "## Node Information"
                    nodeInfo = conn.getInfo()
                    print "%-20s %s"    % (_("CPU model:")         ,nodeInfo[0])
                    print "%-20s %s"    % (_("CPU(s):")            ,nodeInfo[2])
                    print "%-20s %s MHz"% (_("CPU frequency:")     ,nodeInfo[3])
                    print "%-20s %s"    % (_("CPU socket(s):")     ,nodeInfo[5])
                    print "%-20s %s"    % (_("Core(s) per socket:"),nodeInfo[6])
                    print "%-20s %s"    % (_("Thread(s) per core:"),nodeInfo[7])
                    print "%-20s %s"    % (_("NUMA cell(s):")      ,nodeInfo[4])
                    print "%-20s %lu kB"% (_("Memory Size:")  ,(float)(nodeInfo[1])*1024)

                if opts.all is True or opts.list is True:
                    """ Show dom list """
                    print ""
                    print "## Domain List"
                    state_flags = [
                                  "no state",    # VIR_DOMAIN_NOSTATE
                                  "running",     # VIR_DOMAIN_RUNNING
                                  "idle",        # VIR_DOMAIN_BLOCKED
                                  "paused",      # VIR_DOMAIN_PAUSED
                                  "in shutdown", # VIR_DOMAIN_SHUTDOWN
                                  "shut off",    # VIR_DOMAIN_SHUTOFF
                                  "crashed",     # VIR_DOMAIN_CRASHED
                                  ]
                    #print "%3s %-20s %s" %(_("Id"), _("Name"), _("State"))
                    #print "----------------------------------"
                    print "%3s %-20s %-12s %-37s %-10s %-12s %-12s %-3s %-12s" %(_("Id"), _("Name"), _("State"), _("UUID"), _("Autostart"), _("MaxMem"), _("Memory"), _("Vcpus"), _("CPUTime"), )
                    print "---------------------------------------------------------------------------"

                    domains_ids = conn.listDomainsID()
                    for id in domains_ids:
                        dom = conn.lookupByID(id)
                        name    = dom.name()
                        domID   = id
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %("-", name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %(domID, name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])

                    defined_domains = conn.listDefinedDomains()
                    for name in defined_domains:
                        dom = conn.lookupByName(name)
                        #print dom.memoryStats()
                        domID   = dom.ID()
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %("-", name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %(domID, name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])

                if opts.all is True or opts.netlist is True:
                    """ Show net list """
                    print ""
                    print "## Network List"
                    #print "%-20s %-10s %-10s" %(_("Name"), _("State"), _("Autostart"))
                    #print "-----------------------------------------"
                    print "%-20s %-10s %-37s %-10s" %(_("Name"), _("State"), _("UUID"), _("Autostart"), )
                    print "--------------------------------------------------------------------------"
                    networks = conn.listNetworks()
                    for name in networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Active"), uuid, locale_autostart)

                    defined_networks = conn.listDefinedNetworks()
                    for name in defined_networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Inactive"), uuid, locale_autostart)

                if opts.all is True or opts.poollist is True:
                    """ Show pool list """
                    #taizoa
                    print ""
                    print "## Pool List"
                    print "%-20s %-10s %-37s %-10s" %(_("Name"), _("State"), _("UUID"), _("Autostart"), )
                    print "--------------------------------------------------------------------------"
                    pools = conn.listStoragePools()
                    for name in pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Active"), uuid, locale_autostart)

                    defined_pools = conn.listDefinedStoragePools()
                    for name in defined_pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Inactive"), uuid, locale_autostart)

            except:
                pass

        if opts.all is True:
            """ Show available uris """
            print ""
            print "## Available URIs"
            for mech,uri in available_virt_uris().iteritems():
               print uri

            """ Show available mechs """
            print ""
            print "## Available mechanisms"
            for mech in available_virt_mechs():
               print mech

            """ Show installed packages """
            print ""
            print "## Installed packages"
            (rc,res) = execute_command(["rpm","-qa",'--queryformat=%{NAME}\t%{VERSION}\t%{RELEASE}\t%{INSTALLTIME}\t%{BUILDHOST}\n'])
            if rc == 0:
                print "%-25s %-10s %-10s %-20s" %(_("Name"), _("Version"), _("Release"), _("InstallTime"), )
                print "------------------------------------------------------------------"
                p = re.compile("hde\.co\.jp")
                output = []
                for aline in res:
                    arr = aline.split("\t")
                    if p.search(arr[4]):
                        str = "%-25s %-10s %-10s %-20s" %(arr[0],arr[1],arr[2],time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(arr[3]))),)
                        output.append(str)
                print "\n".join(sorted(output))

        finish_msg = _("Completed on %s") % time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
        print ""
        print "# " + finish_msg

        return True
Exemple #12
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()
Exemple #13
0
    def process(self):
        (opts, args) = getopts()

        start_msg = _("Generated by %s on %s") % (
            prog_name, time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
        print "# " + start_msg

        if is_executable(COMMAND_VIRSH):
            old_lang = os.environ.get('LANG')
            os.environ['LANG'] = "C"

            if opts.all is True or (opts.list is not True
                                    and opts.netlist is not True
                                    and opts.nodeinfo is not True
                                    and opts.poollist is not True):
                """ Show version """
                print ""
                print "## Version"
                (rc, res) = execute_command([COMMAND_VIRSH, "version"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line
                self.showKaresansuiVersion()

            if opts.all is True:
                """ Show uri """
                print ""
                print "## URI"
                (rc, res) = execute_command([COMMAND_VIRSH, "uri"])
                if rc == 0:
                    print _("Connecting URI: %s") % (res[0])
                """ Show hostname """
                print ""
                print "## Hostname"
                (rc, res) = execute_command([COMMAND_VIRSH, "hostname"])
                if rc == 0:
                    print _("Hypervisor hostname: %s") % (res[0])

            if opts.all is True or opts.nodeinfo is True:
                """ Show nodeinfo """
                print ""
                print "## Node Information"
                (rc, res) = execute_command([COMMAND_VIRSH, "nodeinfo"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.list is True:
                """ Show dom list """
                print ""
                print "## Domain List"
                (rc, res) = execute_command([COMMAND_VIRSH, "list", "--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.netlist is True:
                """ Show net list """
                print ""
                print "## Network List"
                (rc,
                 res) = execute_command([COMMAND_VIRSH, "net-list", "--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.poollist is True:
                """ Show pool list """
                print ""
                print "## Pool List"
                (rc,
                 res) = execute_command([COMMAND_VIRSH, "pool-list", "--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            os.environ['LANG'] = old_lang
        else:
            try:
                conn = libvirt.openReadOnly(None)
                hypervisor = conn.getType()

                if opts.all is True or (opts.list is not True
                                        and opts.netlist is not True
                                        and opts.nodeinfo is not True
                                        and opts.poollist is not True):
                    """ Show version """
                    print ""
                    print "## Version"
                    ret = libvirtmod.virGetVersion(hypervisor)
                    libVersion = ret[0]
                    apiVersion = ret[1]

                    libVersion_major = libVersion / 1000000
                    libVersion %= 1000000
                    libVersion_minor = libVersion / 1000
                    libVersion_rel = libVersion % 1000
                    apiVersion_major = apiVersion / 1000000
                    apiVersion %= 1000000
                    apiVersion_minor = apiVersion / 1000
                    apiVersion_rel = apiVersion % 1000

                    print _("Using library: libvir %d.%d.%d") % (
                        libVersion_major, libVersion_minor, libVersion_rel)
                    print _("Using API: %s %d.%d.%d") % (
                        hypervisor, apiVersion_major, apiVersion_minor,
                        apiVersion_rel)

                    try:
                        # See https://www.redhat.com/archives/libvir-list/2010-January/msg00723.html
                        ret = libvirtmod.virConnectGetVersion(conn._o)
                        hvVersion = ret
                        hvVersion_major = hvVersion / 1000000
                        hvVersion %= 1000000
                        hvVersion_minor = hvVersion / 1000
                        hvVersion_rel = hvVersion % 1000
                        print _("Running hypervisor: %s %d.%d.%d") % (
                            hypervisor, hvVersion_major, hvVersion_minor,
                            hvVersion_rel)
                    except:
                        if hypervisor == "QEMU":
                            (rc, res) = execute_command(["qemu", "--version"])
                            if rc == 0:
                                p = re.compile(
                                    "QEMU PC emulator version ([0-9\.]+),.*")
                                if p.search(res[0]):
                                    qemuVersion = p.sub("\\1", res[0])
                                    print _("Running hypervisor: %s %s") % (
                                        hypervisor, qemuVersion)

                    self.showKaresansuiVersion()

                if opts.all is True:
                    """ Show uri """
                    print ""
                    print "## URI"
                    uri = conn.getURI()
                    print _("Connecting URI: %s") % (uri)
                    """ Show hostname """
                    print ""
                    print "## Hostname"
                    hostname = conn.getHostname()
                    print _("Hypervisor hostname: %s") % (hostname)

                if opts.all is True or opts.nodeinfo is True:
                    """ Show nodeinfo """
                    print ""
                    print "## Node Information"
                    nodeInfo = conn.getInfo()
                    print "%-20s %s" % (_("CPU model:"), nodeInfo[0])
                    print "%-20s %s" % (_("CPU(s):"), nodeInfo[2])
                    print "%-20s %s MHz" % (_("CPU frequency:"), nodeInfo[3])
                    print "%-20s %s" % (_("CPU socket(s):"), nodeInfo[5])
                    print "%-20s %s" % (_("Core(s) per socket:"), nodeInfo[6])
                    print "%-20s %s" % (_("Thread(s) per core:"), nodeInfo[7])
                    print "%-20s %s" % (_("NUMA cell(s):"), nodeInfo[4])
                    print "%-20s %lu kB" % (_("Memory Size:"),
                                            (float)(nodeInfo[1]) * 1024)

                if opts.all is True or opts.list is True:
                    """ Show dom list """
                    print ""
                    print "## Domain List"
                    state_flags = [
                        "no state",  # VIR_DOMAIN_NOSTATE
                        "running",  # VIR_DOMAIN_RUNNING
                        "idle",  # VIR_DOMAIN_BLOCKED
                        "paused",  # VIR_DOMAIN_PAUSED
                        "in shutdown",  # VIR_DOMAIN_SHUTDOWN
                        "shut off",  # VIR_DOMAIN_SHUTOFF
                        "crashed",  # VIR_DOMAIN_CRASHED
                    ]
                    #print "%3s %-20s %s" %(_("Id"), _("Name"), _("State"))
                    #print "----------------------------------"
                    print "%3s %-20s %-12s %-37s %-10s %-12s %-12s %-3s %-12s" % (
                        _("Id"),
                        _("Name"),
                        _("State"),
                        _("UUID"),
                        _("Autostart"),
                        _("MaxMem"),
                        _("Memory"),
                        _("Vcpus"),
                        _("CPUTime"),
                    )
                    print "---------------------------------------------------------------------------"

                    domains_ids = conn.listDomainsID()
                    for id in domains_ids:
                        dom = conn.lookupByID(id)
                        name = dom.name()
                        domID = id
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                "-", name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                domID, name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])

                    defined_domains = conn.listDefinedDomains()
                    for name in defined_domains:
                        dom = conn.lookupByName(name)
                        #print dom.memoryStats()
                        domID = dom.ID()
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                "-", name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                domID, name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])

                if opts.all is True or opts.netlist is True:
                    """ Show net list """
                    print ""
                    print "## Network List"
                    #print "%-20s %-10s %-10s" %(_("Name"), _("State"), _("Autostart"))
                    #print "-----------------------------------------"
                    print "%-20s %-10s %-37s %-10s" % (
                        _("Name"),
                        _("State"),
                        _("UUID"),
                        _("Autostart"),
                    )
                    print "--------------------------------------------------------------------------"
                    networks = conn.listNetworks()
                    for name in networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Active"), uuid, locale_autostart)

                    defined_networks = conn.listDefinedNetworks()
                    for name in defined_networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Inactive"), uuid, locale_autostart)

                if opts.all is True or opts.poollist is True:
                    """ Show pool list """
                    #taizoa
                    print ""
                    print "## Pool List"
                    print "%-20s %-10s %-37s %-10s" % (
                        _("Name"),
                        _("State"),
                        _("UUID"),
                        _("Autostart"),
                    )
                    print "--------------------------------------------------------------------------"
                    pools = conn.listStoragePools()
                    for name in pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Active"), uuid, locale_autostart)

                    defined_pools = conn.listDefinedStoragePools()
                    for name in defined_pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Inactive"), uuid, locale_autostart)

            except:
                pass

        if opts.all is True:
            """ Show available uris """
            print ""
            print "## Available URIs"
            for mech, uri in available_virt_uris().iteritems():
                print uri
            """ Show available mechs """
            print ""
            print "## Available mechanisms"
            for mech in available_virt_mechs():
                print mech
            """ Show installed packages """
            print ""
            print "## Installed packages"
            (rc, res) = execute_command([
                "rpm", "-qa",
                '--queryformat=%{NAME}\t%{VERSION}\t%{RELEASE}\t%{INSTALLTIME}\t%{BUILDHOST}\n'
            ])
            if rc == 0:
                print "%-25s %-10s %-10s %-20s" % (
                    _("Name"),
                    _("Version"),
                    _("Release"),
                    _("InstallTime"),
                )
                print "------------------------------------------------------------------"
                p = re.compile("hde\.co\.jp")
                output = []
                for aline in res:
                    arr = aline.split("\t")
                    if p.search(arr[4]):
                        str = "%-25s %-10s %-10s %-20s" % (
                            arr[0],
                            arr[1],
                            arr[2],
                            time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime(float(arr[3]))),
                        )
                        output.append(str)
                print "\n".join(sorted(output))

        finish_msg = _("Completed on %s") % time.strftime(
            "%Y/%m/%d %H:%M:%S", time.localtime())
        print ""
        print "# " + finish_msg

        return True
Exemple #14
0
    def _POST(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()
        if model.attribute == 0 and model.hypervisor == 1:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == 2:
            uri = uris["KVM"]
        else:
            uri = None

        if not validates_network(self):
            self.logger.debug("Network creation failed. Did not validate.")
            return web.badrequest(self.view.alert)

        name       = self.input.name
        cidr       = self.input.cidr
        dhcp_start = self.input.dhcp_start
        dhcp_end   = self.input.dhcp_end
        bridge     = self.input.bridge

        # We support only 'nat' for forward-mode.
        forward_mode = ''
        if is_param(self.input, 'forward_mode'):
            if self.input.forward_mode == 'nat':
                forward_mode = 'nat'

        try:
            autostart = self.input.autostart
        except:
            autostart = "no"

        # Check if the name is available (not already used).
        kvc = KaresansuiVirtConnection(uri)
        try:
            try:
                kvc.search_kvn_networks(name)
                self.logger.debug("Network name '%s' already used." % name)
                url = '%s/%s/%s.part' % (web.ctx.home, web.ctx.path, name)
                self.logger.debug("Returning url %s as Location." % url)
                return web.conflict(url)
            except KaresansuiVirtException, e:
                # OK
                pass
        finally:
            kvc.close()

        # spin off create job
        options = {'dhcp-start': dhcp_start,
                   'dhcp-end'  : dhcp_end,
                   'bridge-name'    : bridge,
                   'forward-mode'   : forward_mode,
                   'autostart' : autostart,
                  }

        self.logger.debug('spinning off network_create_job name=%s, cidr=%s, options=%s' % (name, cidr, options))
        host = findbyhost1(self.orm, host_id)
        #network_create_job(self, name, cidr, host, options)

        options['name'] = name
        options['cidr'] = cidr

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], VIRT_COMMAND_CREATE_NETWORK), options)

        # Job Registration
        _jobgroup = JobGroup('Create Network: %s' % name, karesansui.sheconf['env.uniqkey'])
        _jobgroup.jobs.append(Job('Create Network', 0, _cmd))
        _machine2jobgroup = m2j_new(machine=host,
                                    jobgroup_id=-1,
                                    uniq_key=karesansui.sheconf['env.uniqkey'],
                                    created_user=self.me,
                                    modified_user=self.me,
                                    )

        save_job_collaboration(self.orm,
                               self.pysilhouette.orm,
                               _machine2jobgroup,
                               _jobgroup,
                               )

        self.logger.debug('(Create network) Job group id==%s', _jobgroup.id)
        url = '%s/job/%s.part' % (web.ctx.home, _jobgroup.id)
        self.logger.debug('Returning Location: %s' % url)

        return web.accepted()