Example #1
0
 def process(self):
     conn = KaresansuiVirtConnection()
     try:
         guests = conn.search_guests()
 
         nodeinfo = conn.get_nodeinfo()
         
         infos = []
         for guest in guests:
             id = guest.ID()
             if id > -1:
                 name = guest.name()
                 print name
                 info = guest.info()
                 maxMem = info[1]
                 memory = info[2]
                 
                 pcentCurrMem = memory * 100.0 / (nodeinfo["memory"]*1024)
                 pcentMaxMem  = maxMem * 100.0 / (nodeinfo["memory"]*1024)
                 
                 print "%.3f%%" % pcentCurrMem
                 #print pcentMaxMem
                 
         return True
     
     finally:
         conn.close()
Example #2
0
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        model = findbyguest1(self.orm, guest_id)

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

            info = virt.get_graphics_info()
            self.view.checked_listen_all = ""
            self.view.checked_listen_lo = "checked"
            try:
                if info["setting"]["listen"] == "0.0.0.0":
                    self.view.checked_listen_all = "checked"
                    self.view.checked_listen_lo = ""
            except:
                pass

            self.view.VMType = virt.get_info()['VMType']
            self.view.keymaps = eval("get_keymaps(%s_KEYMAP_DIR)" % self.view.VMType.upper())
            self.view.info = info
            self.view.guest = model

        finally:
            kvc.close()
            
        return True
Example #3
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.network.set_network_name(opts.name)
            flag = None

            if opts.enable is True:
                flag = True
            elif opts.disable is True:
                flag = False
            else:
                raise KssCommandException(
                    'either %s options must be specified.' %
                    '--enable or --disable')

            self.up_progress(10)
            ret = conn.autostart_network(flag)
            if ret is False:
                raise KssCommandException(
                    'Failed to set autostart flag. - net=%s flag=%s' %
                    (opts.name, flag))
            self.up_progress(40)

            self.logger.info('Set autostart flag. - net=%s flag=%s' %
                             (opts.name, flag))
            print >> sys.stdout, _('Set autostart flag. - net=%s flag=%s') % (
                opts.name, flag)

            return True
        finally:
            conn.close()
Example #4
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        network_name = param[1]
        if not (network_name and host_id):
            return web.badrequest()

        kvc = KaresansuiVirtConnection()
        try:
            try:
                network = kvc.search_kvn_networks(network_name)[
                    0]  # throws KaresansuiVirtException
                info = network.get_info()
            except KaresansuiVirtException, e:
                # network not found
                self.logger.debug("Network not found. name=%s" % network_name)
                return web.notfound()
        finally:
            kvc.close()

        cidr = '%s/%s' % (info['ip']['address'], info['ip']['netmask'])
        network = dict(
            name=info['name'],
            cidr=cidr,
            dhcp_start=info['dhcp']['start'],
            dhcp_end=info['dhcp']['end'],
            forward_dev=info['forward']['dev'],
            forward_mode=info['forward']['mode'],
            bridge=info['bridge']['name'],
        )
        self.view.info = info
        self.view.network = network
        return True
Example #5
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.network.set_network_name(opts.name)
            flag = None

            if opts.enable is True:
                flag = True
            elif opts.disable is True:
                flag = False
            else:
                raise KssCommandException('either %s options must be specified.' % '--enable or --disable')

            self.up_progress(10)
            ret = conn.autostart_network(flag)
            if ret is False:
                raise KssCommandException('Failed to set autostart flag. - net=%s flag=%s' % (opts.name,flag))
            self.up_progress(40)

            self.logger.info('Set autostart flag. - net=%s flag=%s' % (opts.name,flag))
            print >>sys.stdout, _('Set autostart flag. - net=%s flag=%s') % (opts.name,flag)

            return True
        finally:
            conn.close()
Example #6
0
    def _GET(self, *param, **params):
        """<comment-ja>
        ネットワークがアクティブかどうかのステータス
         - inactive = 0
         - active = 1
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # TODO valid
        network_name = param[1]
        if not network_name:
            return web.badrequest()

        kvc = KaresansuiVirtConnection()
        try:
            kvn = kvc.search_kvn_networks(network_name)[0]
            status = NETWORK_INACTIVE
            if kvn.is_active():
                status = NETWORK_ACTIVE

            if self.__template__["media"] == 'json':
                self.view.status = json_dumps(status)
            else:
                self.view.status = status

            self.__template__.dir = 'hostby1networkby1'
        finally:
            kvc.close()

        return True
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # TODO valid
        network_name = param[1]
        if not network_name:
            return web.notfound()

        if validates_nw_status(self) is False:
            return web.badrequest(self.view.alert)

        status = int(self.input.status)

        kvc = KaresansuiVirtConnection()
        try:
            kvn = kvc.search_kvn_networks(network_name)[0]
            if status == NETWORK_INACTIVE:
                # Stop network
                network_start_stop_job(self, host_id, network_name, 'stop')
                return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media']))
            elif status == NETWORK_ACTIVE:
                # Start network
                network_start_stop_job(self, host_id, network_name, 'start')
                return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media']))
            else:
                return web.badrequest()
        finally:
            kvc.close()
Example #8
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            self.up_progress(10)

            if not opts.mac:
                opts.mac = generate_mac_address()

            conn.guest.append_interface(opts.mac,opts.bridge,opts.network)
            self.up_progress(50)
        finally:
            conn.close()

        self.logger.info('Added interface device. - dom=%s mac=%s bridge=%s network=%s' \
                         % (opts.name, opts.mac, opts.bridge, opts.network))
        print >>sys.stdout, _('Added interface device. - dom=%s mac=%s bridge=%s network=%s') \
              % (opts.name, opts.mac, opts.bridge, opts.network)

        return True
    def _GET(self, *param, **params):
        """<comment-ja>
        ネットワークがアクティブかどうかのステータス
         - inactive = 0
         - active = 1
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # TODO valid
        network_name =param[1]
        if not network_name:
            return web.badrequest()

        kvc = KaresansuiVirtConnection()
        try:
            kvn = kvc.search_kvn_networks(network_name)[0]
            status = NETWORK_INACTIVE
            if kvn.is_active():
                status = NETWORK_ACTIVE

            if self.__template__["media"] == 'json':
                self.view.status = json_dumps(status)
            else:
                self.view.status = status

            self.__template__.dir = 'hostby1networkby1'
        finally:
            kvc.close()

        return True
Example #10
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()
            if not (opts.name in active_networks
                    or opts.name in inactive_networks):
                raise KssCommandException(
                    'Could not find the specified network. - net=%s' %
                    (opts.name))

            self.up_progress(10)
            try:
                conn.delete_network(opts.name)
            except:
                raise KssCommandException(
                    'Failed to delete network. - net=%s' % (opts.name))

            self.up_progress(20)
            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()
            if opts.name in active_networks or opts.name in inactive_networks:
                raise KssCommandException(
                    'Failed to delete the network. - net=%s' % (opts.name))

            self.logger.info('Deleted network. - net=%s' % (opts.name))
            print >> sys.stdout, _('Deleted network. - net=%s') % (opts.name)
            return True
        finally:
            conn.close()
Example #11
0
    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
Example #12
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        network_name = param[1]
        if not (network_name and host_id):
            return web.badrequest()

        kvc = KaresansuiVirtConnection()
        try:
            try:
                network = kvc.search_kvn_networks(network_name)[0] # throws KaresansuiVirtException
                info = network.get_info()
            except KaresansuiVirtException, e:
                # network not found
                self.logger.debug("Network not found. name=%s" % network_name)
                return web.notfound()
        finally:
            kvc.close()

        cidr = '%s/%s' % (info['ip']['address'], info['ip']['netmask'])
        network = dict(name=info['name'],
                       cidr=cidr,
                       dhcp_start=info['dhcp']['start'],
                       dhcp_end=info['dhcp']['end'],
                       forward_dev=info['forward']['dev'],
                       forward_mode=info['forward']['mode'],
                       bridge=info['bridge']['name'],
                       )
        self.view.info = info
        self.view.network = network
        return True
Example #13
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            active_guests = conn.list_active_guest()
            inactive_guests = conn.list_inactive_guest()
            if opts.name in active_guests or opts.name in inactive_guests:
                try:
                    self.up_progress(10)
                    conn.guest.set_vcpus(vcpus=opts.vcpus,max_vcpus=opts.max_vcpus)
                    self.up_progress(20)
                    info = conn.guest.get_vcpus_info()
                    self.up_progress(10)

                    self.logger.info('Set vcpus. - dom=%s vcpus=%s max_vcpus=%s bootup_vcpus=%s' \
                                     % (opts.name, info['vcpus'], info['max_vcpus'], info['bootup_vcpus']))
                    print >>sys.stdout, _('Set vcpus. - dom=%s vcpus=%s max_vcpus=%s bootup_vcpus=%s') \
                          % (opts.name, info['vcpus'], info['max_vcpus'], info['bootup_vcpus'])

                except Exception, e:
                    self.logger.error('Failed to set vcpus. - dom=%s' % (opts.name))
                    print >>sys.stderr, _('Failed to set vcpus. - dom=%s') % (opts.name)
                    raise e

            else:
Example #14
0
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        if is_int(param[2]) is False:
            return web.badrequest()

        disk_id = int(param[2])

        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()

        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.notfound()

            virt = kvc.search_kvg_guests(domname)[0]

            guest = MergeGuest(model, virt)
            self.view.guest = guest
            self.view.disk_info = virt.get_disk_info()[disk_id]
        finally:
            kvc.close()

        return True
Example #15
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # TODO valid
        network_name = param[1]
        if not network_name:
            return web.notfound()

        if validates_nw_status(self) is False:
            return web.badrequest(self.view.alert)

        status = int(self.input.status)

        kvc = KaresansuiVirtConnection()
        try:
            kvn = kvc.search_kvn_networks(network_name)[0]
            if status == NETWORK_INACTIVE:
                # Stop network
                network_start_stop_job(self, host_id, network_name, 'stop')
                return web.accepted(
                    "/host/%s/network/%s.%s" %
                    (host_id, network_name, self.__template__['media']))
            elif status == NETWORK_ACTIVE:
                # Start network
                network_start_stop_job(self, host_id, network_name, 'start')
                return web.accepted(
                    "/host/%s/network/%s.%s" %
                    (host_id, network_name, self.__template__['media']))
            else:
                return web.badrequest()
        finally:
            kvc.close()
Example #16
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

        # Pool
        try:
            kvc = KaresansuiVirtConnection()
            inactive_pool = kvc.list_inactive_storage_pool()
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

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

                    vols_info = []
                    for vol_obj in vols_obj:
                        vols_info.append(vol_obj.get_info())
        finally:
            kvc.close()

        self.view.pools_info = pools_info

        if self.is_mode_input() is True:
            # .input
            try:
                kvc = KaresansuiVirtConnection()

                already_iqn = []
                for pool in pools:
                    pool_iqn = kvc.get_storage_pool_sourcedevicepath(pool)
                    if pool_iqn:
                        already_iqn.append(pool_iqn)
            finally:
                kvc.close()

            network_storages = get_iscsi_cmd(self, host_id)
            if network_storages is False:
                self.logger.debug("Get iSCSI command failed. Return to timeout")
                return web.internalerror("Internal Server Error. (Timeout)")

            available_network_storages = []
            for i in range(len(network_storages)):
                if network_storages[i]["iqn"] not in already_iqn and network_storages[i]["activity"] == 1:
                    available_network_storages.append(network_storages[i])

            self.view.network_storages = available_network_storages
            self.view.pool_types = (STORAGE_POOL_TYPE["TYPE_DIR"], STORAGE_POOL_TYPE["TYPE_ISCSI"])

        return True
Example #17
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()
            if not (opts.name in active_networks
                    or opts.name in inactive_networks):
                raise KssCommandException('Network not found. - net=%s' %
                                          (opts.name))

            self.up_progress(10)
            conn.stop_network(opts.name)
            self.up_progress(40)

            if opts.name in conn.list_active_network():
                raise KssCommandException('Failed to stop network. - net=%s' %
                                          (opts.name))

            self.logger.info('Stopped network. - net=%s' % (opts.name))
            print >> sys.stdout, _('Stopped network. - net=%s') % (opts.name)

            return True
        finally:
            conn.close()
Example #18
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            active_guests = conn.list_active_guest()
            inactive_guests = conn.list_inactive_guest()

            if opts.name in active_guests or opts.name in inactive_guests:
                try:
                    self.up_progress(10)
                    conn.suspend_guest()
                    self.up_progress(40)
                except:
                    raise KssCommandException('Failed to suspend guest. - dom=%s' % (opts.name))

                self.up_progress(10)
                status = conn.guest.status()
                self.up_progress(10)
                if status == VIR_DOMAIN_PAUSED:
                    self.logger.info('Succeeded to suspend guest. - dom=%s' % (opts.name))
                    print >>sys.stdout, _('Succeeded to suspend guest. - dom=%s') % (opts.name)

            else:
                raise KssCommandException(
                    'Could not find guest. - dom=%s' % (opts.name))

            return True

        finally:
            conn.close()
Example #19
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()
            if not (opts.name in active_networks or opts.name in inactive_networks):
                raise KssCommandException('Could not find the specified network. - net=%s' % (opts.name))

            self.up_progress(10)
            try:
                conn.delete_network(opts.name)
            except:
                raise KssCommandException('Failed to delete network. - net=%s' % (opts.name))

            self.up_progress(20)
            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()
            if opts.name in active_networks or opts.name in inactive_networks:
                raise KssCommandException('Failed to delete the network. - net=%s' % (opts.name))

            self.logger.info('Deleted network. - net=%s' % (opts.name))
            print >>sys.stdout, _('Deleted network. - net=%s') % (opts.name)
            return True
        finally:
            conn.close()
Example #20
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            forward = {
                "dev": opts.forward_dev,
                "mode": opts.forward_mode,
            }
            bridge = opts.bridge_name

            if opts.autostart == "yes":
                autostart = True
            else:
                autostart = False

            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()

            self.up_progress(10)
            if opts.name in active_networks or opts.name in inactive_networks:
                raise KssCommandException('network already exists. - net=%s' %
                                          (opts.name))

            self.up_progress(10)
            try:
                conn.create_network(opts.name,
                                    opts.cidr,
                                    opts.dhcp_start,
                                    opts.dhcp_end,
                                    forward,
                                    bridge,
                                    autostart=autostart)
            except:
                raise KssCommandException(
                    'Failed to create network. - net=%s' % (opts.name))

            self.up_progress(40)
            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()
            if not (opts.name in active_networks
                    or opts.name in inactive_networks):
                raise KssCommandException(
                    'Failed to create the network. - net=%s' % (opts.name))

            self.logger.info('Created network. - net=%s' % (opts.name))
            print >> sys.stdout, _('Created network. - net=%s') % (opts.name)
            self.up_progress(10)

            return True
        finally:
            conn.close()
Example #21
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            forward = {"dev": opts.forward_dev,
                       "mode": opts.forward_mode,
                       }
            bridge  = opts.bridge_name

            if opts.autostart == "yes":
                autostart = True
            else:
                autostart = False

            self.up_progress(20)
            try:
                conn.update_network(opts.name, opts.cidr, opts.dhcp_start, opts.dhcp_end, forward, bridge, autostart=autostart)
            except:
                self.logger.error('Failed to update network. - net=%s' % (opts.name))
                raise

            # The network should be active now.
            # If not, we're going to start it up.
            active_networks = conn.list_active_network()
            if not (opts.name in active_networks):
                try:
                    conn.start_network(opts.name)
                except KaresansuiVirtException, e:
                    # try to bring down existing bridge
                    kvn = conn.search_kvn_networks(opts.name)[0]
                    try:
                        bridge_name = kvn.get_info()['bridge']['name']
                    except KeyError:
                        pass

                    ret, res = execute_command([NETWORK_IFCONFIG_COMMAND, bridge_name, 'down'])
                    ret, res = execute_command([NETWORK_BRCTL_COMMAND, 'delbr', bridge_name])

                    # try again
                    conn.start_network(opts.name)
                    self.up_progress(10)

            self.up_progress(10)
            active_networks = conn.list_active_network()
            if not (opts.name in active_networks):
                raise KssCommandException('Updated network but it\'s dead. - net=%s' % (opts.name))

            self.logger.info('Updated network. - net=%s' % (opts.name))
            print >>sys.stdout, _('Updated network. - net=%s') % (opts.name)
            return True
Example #22
0
class Tree(Rest):
    def _post(self, f):
        ret = Rest._post(self, f)
        if hasattr(self, "kvc") is True:
            self.kvc.close()
        return ret

    @auth
    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
Example #23
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            active_networks = conn.list_active_network()
            inactive_networks = conn.list_inactive_network()
            if not (opts.name in active_networks or opts.name in inactive_networks):
                raise KssCommandException('Network not found. - net=%s' % (opts.name))

            self.up_progress(10)
            conn.stop_network(opts.name)
            self.up_progress(40)

            if opts.name in conn.list_active_network():
                raise KssCommandException('Failed to stop network. - net=%s' % (opts.name))

            self.logger.info('Stopped network. - net=%s' % (opts.name))
            print >>sys.stdout, _('Stopped network. - net=%s') % (opts.name)

            return True
        finally:
            conn.close()
Example #24
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            active_guests = conn.list_active_guest()
            inactive_guests = conn.list_inactive_guest()
            if opts.name in active_guests or opts.name in inactive_guests:
                try:
                    self.up_progress(10)
                    conn.destroy_guest()
                    self.up_progress(40)
                except Exception, e:
                    self.logger.error('Failed to destroy guest. - dom=%s' %
                                      (opts.name))
                    print >> sys.stderr, _(
                        'Failed to destroy guest. - dom=%s') % (opts.name)
                    raise e

                status = conn.guest.status()

                self.up_progress(10)

                if status == VIR_DOMAIN_SHUTOFF or status == VIR_DOMAIN_SHUTDOWN:
                    self.logger.info('Succeeded to destroy guest. - dom=%s' %
                                     (opts.name))
                    print >> sys.stdout, _(
                        'Succeeded to destroy guest. - dom=%s') % (opts.name)

            else:
Example #25
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
Example #26
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
Example #27
0
    def _PUT(self, *param, **params):

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

        if is_int(param[2]) is False:
            return web.notfound()
        nic_id = int(param[2])

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

        model = findbyguest1(self.orm, guest_id)
        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname:
                return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            old_mac = virt.get_interface_info()[nic_id]["mac"]["address"]
            nic_info = virt.get_interface_info()
        finally:
            kvc.close()

        new_mac = self.input.mac_address

        if old_mac != new_mac:
            f_chk = True
            for x in nic_info:
                if x["mac"]["address"] == new_mac:
                    f_chk = False
                    break
            if f_chk is False:
                return web.badrequest(_("Specified MAC address is already defined."))

            self.logger.debug(
                "spinning off change_mac_job dom=%s, from_mac=%s, to_mac=%s" % (domname, old_mac, new_mac)
            )
            if change_mac_job(self, model, domname, old_mac, new_mac) is True:
                return web.accepted(url=web.ctx.path)
            else:
                return False

        else:
            return web.accepted(url=web.ctx.path)
Example #28
0
class Tree(Rest):

    def _post(self, f):
        ret = Rest._post(self, f)
        if hasattr(self, "kvc") is True:
            self.kvc.close()
        return ret

    @auth
    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
Example #29
0
class Tree(Rest):
    def _post(self, f):
        ret = Rest._post(self, f)
        if hasattr(self, "kvc") is True:
            self.kvc.close()
        return ret

    @auth
    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
Example #30
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)
            conn.guest.delete_interface(opts.mac)
            self.up_progress(50)

            self.logger.info('Deleted interface device. - dom=%s mac=%s' % (opts.name,opts.mac))
            print >>sys.stdout, _('Deleted interface device. - dom=%s mac=%s') % (opts.name, opts.mac)

            return True
        finally:
            conn.close()
Example #31
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)
            self.up_progress(10)
            conn.guest.modify_mac_address(opts.old,opts.new)
            self.up_progress(40)
            self.logger.info('Set MAC address. - dom=%s from=%s to=%s' % (opts.name,opts.old, opts.new))
            print >>sys.stdout, _('Set MAC address. - dom=%s from=%s to=%s') % (opts.name, opts.old, opts.new)
            return True

        finally:
            conn.close()
Example #32
0
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.notfound()

            virt = kvc.search_kvg_guests(domname)[0]

            vcpus_info = virt.get_vcpus_info()
            self.view.max_vcpus_limit = kvc.get_max_vcpus()
            self.view.max_vcpus = vcpus_info['bootup_vcpus']
            self.view.vcpus_limit = vcpus_info['max_vcpus']
            self.view.vcpus = vcpus_info['vcpus']

            self.view.cpuTime = virt.get_info()['cpuTime']
            self.view.hypervisor = virt.get_info()['hypervisor']

            self.view.guest = model
        finally:
            kvc.close()

        return True
Example #33
0
def validates_pool_dir(obj, now_pools):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if is_param(obj.input, "pool_name"):
        check = (
            checker.check_string(_("Storage Pool Name"), obj.input.pool_name, CHECK_EMPTY | CHECK_ONLYSPACE, None)
            and check
        )
        if obj.input.pool_name in now_pools:
            check = False
            checker.add_error(_('%s "%s" already exists.') % (_("Storage Pool Name"), obj.input.pool_name))
    else:
        check = False
        checker.add_error(_('"%s" is required.') % _("Storage Pool Name"))

    if is_param(obj.input, "pool_target_path"):
        check = (
            checker.check_directory(
                _("Directory Path"), obj.input.pool_target_path, CHECK_EMPTY | CHECK_STARTROOT | CHECK_NOTROOT
            )
            and check
        )
        try:
            kvc = KaresansuiVirtConnection()

            for pool_name in now_pools:
                target_path = kvc.get_storage_pool_targetpath(pool_name)
                if obj.input.pool_target_path == target_path:
                    check = False
                    checker.add_error(
                        _('Storagepool target path "%s" is already being used.') % (obj.input.pool_target_path)
                    )
        finally:
            kvc.close()

    else:
        check = False
        checker.add_error(_('"%s" is required.') % _("Directory Path"))

    obj.view.alert = checker.errors
    return check
Example #34
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            active_guests = conn.list_active_guest()
            inactive_guests = conn.list_inactive_guest()
            if opts.name in active_guests or opts.name in inactive_guests:
                try:
                    self.up_progress(10)
                    conn.destroy_guest()
                    self.up_progress(40)
                except Exception, e:
                    self.logger.error('Failed to destroy guest. - dom=%s' % (opts.name))
                    print >>sys.stderr, _('Failed to destroy guest. - dom=%s') % (opts.name)
                    raise e

                status = conn.guest.status()

                self.up_progress(10)

                if status == VIR_DOMAIN_SHUTOFF or status == VIR_DOMAIN_SHUTDOWN:
                    self.logger.info('Succeeded to destroy guest. - dom=%s' % (opts.name))
                    print >>sys.stdout, _('Succeeded to destroy guest. - dom=%s') % (opts.name)

            else:
Example #35
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            inactive_storage_pools = conn.list_inactive_storage_pool()
            active_storage_pools = conn.list_active_storage_pool()
            self.up_progress(10)
            if not (opts.name in active_storage_pools or \
                    opts.name in inactive_storage_pools):
                raise KssCommandOptException(
                    'Storage pool does not exist. - pool=%s' % opts.name)

            conn.storage_pool.set_storage_name(opts.name)

            self.up_progress(10)
            flag = None
            if opts.enable:
                flag = True
            elif opts.disable:
                flag = False
            else:
                raise KssCommandException(
                    'ERROR: Execution status information does not exist. enable,disable=%s,%s' \
                    % (str(opts.enable), str(opts.disable)))

            self.up_progress(10)
            if conn.autostart_storage_pool(flag) is False:
                raise KssCommandException(
                    'Failed to autostart storage pool(libvirt). - pool=%s' %
                    (opts.name))

            ret = conn.is_autostart_storage_pool()
            if not (ret is flag):
                raise KssCommandException(
                    'Auto-start failed to set the storage pool. - pool=%s, autostart=%s' \
                    % (opts.name, str(ret)))

            self.up_progress(40)
            if opts.enable:
                self.logger.info('Set autostart storage pool. - pool=%s' %
                                 (opts.name))
                print >> sys.stdout, _(
                    'Set autostart storage pool. - pool=%s') % (opts.name)
            elif opts.disable:
                self.logger.info('Unset autostart storage pool. - pool=%s' %
                                 (opts.name))
                print >> sys.stdout, _(
                    'Unset autostart storage pool. - pool=%s') % (opts.name)

            return True
        finally:
            conn.close()
Example #36
0
 def __init__(self, uri=None, readonly=True):
     self.__prep()
     self.logger.debug(get_inspect_stack())
     try:
         self.kvc = KaresansuiVirtConnection(uri=uri, readonly=readonly)
     except:
         raise KaresansuiVirtSnapshotException(_("Cannot open '%s'") % uri)
     try:
         from libvirtmod import virDomainRevertToSnapshot
         from libvirtmod import virDomainSnapshotCreateXML
         from libvirtmod import virDomainSnapshotCurrent
         from libvirtmod import virDomainSnapshotDelete
         from libvirtmod import virDomainSnapshotGetXMLDesc
         from libvirtmod import virDomainSnapshotLookupByName
     except:
         raise KaresansuiVirtSnapshotException(
             _("Snapshot is not supported by this version of libvirt"))
     self.error_msg = []
Example #37
0
    def _PUT(self, *param, **params):
        """<comment-ja>
        Japanese Comment
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None:
            return web.notfound()

        if is_param(self.input, "memory"):
            memory = int(self.input.memory)
        else:
            memory = None
        max_memory = int(self.input.max_memory)

        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname:
                return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            info = virt.get_info()
            # maxMem = info["maxMem"]
            now_memory = info["memory"]
            mem_info = kvc.get_mem_info()
            nodeinfo = kvc.get_nodeinfo()
        finally:
            kvc.close()

        # valid
        # if (mem_info["host_free_mem"] + (now_memory / 1024)) < memory:
        #    return web.badrequest("Memory value is greater than the maximum memory value. - memory=%s" % self.input.memory)

        options = {}
        options["name"] = domname
        options["maxmem"] = max_memory
        if memory is None:
            options["memory"] = max_memory
        else:
            options["memory"] = memory
        _cmd = dict2command("%s/%s" % (karesansui.config["application.bin.dir"], VIRT_COMMAND_SET_MEMORY), options)
        cmdname = "Set memory"
        _jobgroup = JobGroup(cmdname, karesansui.sheconf["env.uniqkey"])
        _jobgroup.jobs.append(Job("%s command" % cmdname, 0, _cmd))
        _machine2jobgroup = m2j_new(
            machine=model,
            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)
        return web.accepted(url=web.ctx.path)
Example #38
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug(
                "Set storage pool status failed. Did not validate.")
            return web.badrequest(self.view.alert)

        model = findbyhost1(self.orm, host_id)

        # Pool
        try:
            kvc = KaresansuiVirtConnection()
            inactive_pool = kvc.list_inactive_storage_pool()
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            self.view.pools = pools

            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                self.logger.debug(
                    "Set storage pool status failed. Target storage pool not found."
                )
                return web.notfound()

            status = int(self.input.status)
            if status == STORAGE_POOL_START:
                storagepool_start_stop_job(self, model, pools_obj[0], 'start')
            elif status == STORAGE_POOL_STOP:
                if kvc.is_used_storage_pool(
                        name=pools_obj[0].get_storage_name(),
                        active_only=True) is True:
                    self.logger.debug(
                        "Stop storage pool failed. Target storage pool is used by guest."
                    )
                    return web.badrequest(
                        "Target storage pool is used by guest.")
                else:
                    storagepool_start_stop_job(self, model, pools_obj[0],
                                               'stop')
            else:
                self.logger.debug(
                    "Set storage pool status failed. Unknown status type.")
                return web.badrequest()

            return web.accepted()
        finally:
            kvc.close()
Example #39
0
def validates_pool_iscsi(obj, now_pools):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if is_param(obj.input, 'pool_name'):
        check = checker.check_string(_('Storage Pool Name'),
                                     obj.input.pool_name,
                                     CHECK_EMPTY | CHECK_ONLYSPACE,
                                     None,
                                     ) and check
        if obj.input.pool_name in now_pools:
            check = False
            checker.add_error(_('%s "%s" already exists.') % (_('Storage Pool Name'), obj.input.pool_name))
    else:
        check = False
        checker.add_error(_('"%s" is required.') %_('Storage Pool Name'))

    if is_param(obj.input, 'pool_target_iscsi'):
        check = checker.check_string(_('iSCSI Target'),
                                        obj.input.pool_target_iscsi,
                                        CHECK_EMPTY | CHECK_ONLYSPACE,
                                        None,
                                        ) and check
        try:
            kvc = KaresansuiVirtConnection()

            for pool_name in now_pools:
                pool_iqn = kvc.get_storage_pool_sourcedevicepath(pool_name)
                if obj.input.pool_target_iscsi == pool_iqn:
                    check = False
                    checker.add_error(_('Storagepool iSCSI target IQN "%s" is already being used.') % (obj.input.pool_target_iscsi))
        finally:
            kvc.close()

    else:
        check = False
        checker.add_error(_('"%s" is required.') %_('iSCSI Target'))

    obj.view.alert = checker.errors
    return check
Example #40
0
def validates_pool_iscsi(obj, now_pools):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if is_param(obj.input, "pool_name"):
        check = (
            checker.check_string(_("Storage Pool Name"), obj.input.pool_name, CHECK_EMPTY | CHECK_ONLYSPACE, None)
            and check
        )
        if obj.input.pool_name in now_pools:
            check = False
            checker.add_error(_('%s "%s" already exists.') % (_("Storage Pool Name"), obj.input.pool_name))
    else:
        check = False
        checker.add_error(_('"%s" is required.') % _("Storage Pool Name"))

    if is_param(obj.input, "pool_target_iscsi"):
        check = (
            checker.check_string(_("iSCSI Target"), obj.input.pool_target_iscsi, CHECK_EMPTY | CHECK_ONLYSPACE, None)
            and check
        )
        try:
            kvc = KaresansuiVirtConnection()

            for pool_name in now_pools:
                pool_iqn = kvc.get_storage_pool_sourcedevicepath(pool_name)
                if obj.input.pool_target_iscsi == pool_iqn:
                    check = False
                    checker.add_error(
                        _('Storagepool iSCSI target IQN "%s" is already being used.') % (obj.input.pool_target_iscsi)
                    )
        finally:
            kvc.close()

    else:
        check = False
        checker.add_error(_('"%s" is required.') % _("iSCSI Target"))

    obj.view.alert = checker.errors
    return check
Example #41
0
def validates_pool_dir(obj, now_pools):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if is_param(obj.input, 'pool_name'):
        check = checker.check_string(_('Storage Pool Name'),
                                     obj.input.pool_name,
                                     CHECK_EMPTY | CHECK_ONLYSPACE,
                                     None,
                                     ) and check
        if obj.input.pool_name in now_pools:
            check = False
            checker.add_error(_('%s "%s" already exists.') % (_('Storage Pool Name'), obj.input.pool_name))
    else:
        check = False
        checker.add_error(_('"%s" is required.') %_('Storage Pool Name'))

    if is_param(obj.input, 'pool_target_path'):
        check = checker.check_directory(_('Directory Path'),
                                        obj.input.pool_target_path,
                                        CHECK_EMPTY | CHECK_STARTROOT | CHECK_NOTROOT
                                        ) and check
        try:
            kvc = KaresansuiVirtConnection()

            for pool_name in now_pools:
                target_path = kvc.get_storage_pool_targetpath(pool_name)
                if obj.input.pool_target_path == target_path:
                    check = False
                    checker.add_error(_('Storagepool target path "%s" is already being used.') % (obj.input.pool_target_path))
        finally:
            kvc.close()

    else:
        check = False
        checker.add_error(_('"%s" is required.') %_('Directory Path'))

    obj.view.alert = checker.errors
    return check
Example #42
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            try:
                inactive_storage_pools = conn.list_inactive_storage_pool()
                active_storage_pools = conn.list_active_storage_pool()

                self.up_progress(10)

                if not (opts.name in active_storage_pools
                        or opts.name in inactive_storage_pools):
                    raise KssCommandException(
                        'Specified storage pool does not exist. - pool=%s' %
                        opts.name)

                if opts.name in active_storage_pools:
                    raise KssCommandException(
                        'Storage pool is already running. - pool=%s' %
                        opts.name)

                self.up_progress(10)
                if conn.start_storage_pool(opts.name) is False:
                    raise KssCommandException(
                        'Failed to start storage pool. (libvirt) - pool=%s' %
                        (opts.name))

                self.up_progress(40)

                inactive_storage_pools = conn.list_inactive_storage_pool()
                active_storage_pools = conn.list_active_storage_pool()
                if not (opts.name in active_storage_pools):
                    raise KssCommandException(
                        'Could not start the storage pool. - pool=%s' %
                        (opts.name))

                self.logger.info('Start storage pool. - pool=%s' % (opts.name))
                print >> sys.stdout, _('Start storage pool. - pool=%s') % (
                    opts.name)
                return True
            except KssCommandException, e:
                raise e
        finally:
            conn.close()
Example #43
0
    def _DELETE(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        if is_int(param[2]) is False:
            return web.notfound()       

        nic_id = int(param[2])

        model = findbyguest1(self.orm, guest_id)
        
        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            nic_info = virt.get_interface_info()[nic_id]
        finally:
            kvc.close()

        mac = nic_info["mac"]["address"]
        self.logger.debug('spinning off delete_nic_job dom=%s, mac=%s' % (domname, mac))
        if delete_nic_job(self,model,domname,mac) is True:
            return web.accepted()
        else:
            return False
Example #44
0
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        if is_int(param[2]) is False:
            return web.badrequest()

        disk_id = int(param[2])

        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()

        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.notfound()

            virt = kvc.search_kvg_guests(domname)[0]

            guest = MergeGuest(model, virt)
            self.view.guest = guest
            self.view.disk_info = virt.get_disk_info()[disk_id]
        finally:
            kvc.close()

        return True
Example #45
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            self.up_progress(10)
            if not opts.target:
                opts.target = conn.guest.next_disk_target()

            conn.guest.append_disk(opts.disk,
                                   opts.target,
                                   bus=opts.bus,
                                   disk_type=opts.disk_type,
                                   driver_name=opts.driver_name,
                                   driver_type=opts.driver_type,
                                   disk_device=opts.disk_device)
            self.up_progress(50)
        finally:
            conn.close()

        self.logger.info('Appended disk device. - dom=%s target=%s path=%s' \
                         % (opts.name, opts.target, opts.disk))
        print >>sys.stdout, _('Appended disk device. - dom=%s target=%s path=%s') \
              % (opts.name,opts.target,opts.disk)
        return True
Example #46
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            self.up_progress(10)

            if not opts.mac:
                opts.mac = generate_mac_address()

            conn.guest.append_interface(opts.mac, opts.bridge, opts.network)
            self.up_progress(50)
        finally:
            conn.close()

        self.logger.info('Added interface device. - dom=%s mac=%s bridge=%s network=%s' \
                         % (opts.name, opts.mac, opts.bridge, opts.network))
        print >>sys.stdout, _('Added interface device. - dom=%s mac=%s bridge=%s network=%s') \
              % (opts.name, opts.mac, opts.bridge, opts.network)

        return True
Example #47
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)
            flag = None
            if opts.enable:
                flag = True
            if opts.disable:
                flag = False
            self.up_progress(10)
            ret = conn.autostart_guest(flag)
            self.up_progress(40)
        finally:
            conn.close()

        if ret is False:
            raise KssCommandException('Failed to set autostart flag. - dom=%s flag=%s' \
                              % (opts.name,flag))

        self.logger.info('Set autostart flag. - dom=%s flag=%s' \
                         % (opts.name,flag))
        print >>sys.stdout, _('Set autostart flag. - dom=%s flag=%s') \
              % (opts.name,flag)
        return True
Example #48
0
    def process(self):
        conn = KaresansuiVirtConnection()
        try:
            guests = conn.search_guests()

            nodeinfo = conn.get_nodeinfo()

            infos = []
            for guest in guests:
                id = guest.ID()
                if id > -1:
                    name = guest.name()
                    print name
                    info = guest.info()
                    maxMem = info[1]
                    memory = info[2]

                    pcentCurrMem = memory * 100.0 / (nodeinfo["memory"] * 1024)
                    pcentMaxMem = maxMem * 100.0 / (nodeinfo["memory"] * 1024)

                    print "%.3f%%" % pcentCurrMem
                    #print pcentMaxMem

            return True

        finally:
            conn.close()
Example #49
0
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.notfound()

            virt = kvc.search_kvg_guests(domname)[0]

            vcpus_info = virt.get_vcpus_info()
            self.view.max_vcpus_limit = kvc.get_max_vcpus()
            self.view.max_vcpus       = vcpus_info['bootup_vcpus']
            self.view.vcpus_limit     = vcpus_info['max_vcpus']
            self.view.vcpus           = vcpus_info['vcpus']

            self.view.cpuTime = virt.get_info()['cpuTime']
            self.view.hypervisor = virt.get_info()['hypervisor']

            self.view.guest = model
        finally:
            kvc.close()
            
        return True
Example #50
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
Example #51
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            active_guests = conn.list_active_guest()
            inactive_guests = conn.list_inactive_guest()
            if opts.name in active_guests or opts.name in inactive_guests:
                try:
                    self.up_progress(10)
                    conn.guest.set_vcpus(vcpus=opts.vcpus,
                                         max_vcpus=opts.max_vcpus)
                    self.up_progress(20)
                    info = conn.guest.get_vcpus_info()
                    self.up_progress(10)

                    self.logger.info('Set vcpus. - dom=%s vcpus=%s max_vcpus=%s bootup_vcpus=%s' \
                                     % (opts.name, info['vcpus'], info['max_vcpus'], info['bootup_vcpus']))
                    print >>sys.stdout, _('Set vcpus. - dom=%s vcpus=%s max_vcpus=%s bootup_vcpus=%s') \
                          % (opts.name, info['vcpus'], info['max_vcpus'], info['bootup_vcpus'])

                except Exception, e:
                    self.logger.error('Failed to set vcpus. - dom=%s' %
                                      (opts.name))
                    print >> sys.stderr, _('Failed to set vcpus. - dom=%s') % (
                        opts.name)
                    raise e

            else:
Example #52
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            conn.set_domain_name(opts.name)

            passwd = None
            if opts.passwd is not None:
                passwd = opts.passwd
            elif opts.passwd_file is not None and os.path.exists(opts.passwd_file):
                try:
                    fp = open(opts.passwd_file, "r")
                    try:
                        self.up_progress(10)
                        fcntl.lockf(fp.fileno(), fcntl.LOCK_SH)
                        try:
                            passwd = fp.readline().strip("\n")
                        finally:
                            fcntl.lockf(fp.fileno(), fcntl.LOCK_UN)

                        self.up_progress(10)
                    finally:
                        fp.close()

                except Exception, e:
                    self.logger.error('Failed to read file. - dom=%s passwd_file=%s' \
                                      % (opts.name,opts.passwd_file))
                    print >>sys.stderr, _('Failed to read file. - dom=%s passwd_file=%s') \
                          % (opts.name,opts.passwd_file)
                    raise e

                os.remove(opts.passwd_file)
                self.up_progress(10)

            elif opts.random_passwd and opts.random_passwd is not None:
                passwd = generate_phrase(8,'23456789abcdefghijkmnpqrstuvwxyz')
Example #53
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)

        step = 100 / opts.count

        for cnt in xrange(0, opts.count):
            self.up_progress(step)
            try:
                print cnt
                conn = KaresansuiVirtConnection(readonly=False)
                print conn
            finally:
                pass
Example #54
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug("Delete storage pool failed. Did not validate.")
            return web.badrequest(self.view.alert)

        # Pool
        try:
            kvc = KaresansuiVirtConnection()
            inactive_pool = kvc.list_inactive_storage_pool()
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            self.view.pools = pools

            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                return web.notfound()

            if kvc.is_used_storage_pool(
                    pools_obj[0].get_storage_name()) is True:
                self.logger.debug(
                    "Delete storage pool failed. Target storage pool is used by guest."
                )
                return web.badrequest("Target storage pool is used by guest.")
        finally:
            kvc.close()

        model = findbyhost1(self.orm, host_id)

        if delete_storage_pool_job(self, model,
                                   pools_obj[0].get_storage_name()) is True:
            self.logger.debug("Delete storage pool success. name=%s" %
                              (pools_obj[0].get_storage_name()))
            return web.accepted()
        else:
            self.logger.debug("Failed delete storage pool. name=%s" %
                              (pools_obj[0].get_storage_name()))
            return False
Example #55
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            try:
                inactive_storage_pools = conn.list_inactive_storage_pool()
                active_storage_pools = conn.list_active_storage_pool()
                self.up_progress(10)
                if not (opts.name in active_storage_pools or \
                        opts.name in inactive_storage_pools):
                    raise KssCommandException('Storage pool does not exist. - pool=%s'
                                          % (opts.name))
                self.up_progress(30)

                if opts.name in conn.list_active_storage_pool():
                    if conn.destroy_storage_pool(opts.name) is False:
                        KssCommandException("Failed to stop the storage pool. - pool=%s"
                                            % (opts.name))
                else:
                    raise KssCommandException('Storage pool is not active. - pool=%s'
                                          % (opts.name))

                self.up_progress(30)

                # check
                if not (opts.name in conn.list_inactive_storage_pool()):
                    KssCommandException("Failed to stop the storage pool. - pool=%s"
                                        % (opts.name))

                self.logger.info('Stop storage pool. - pool=%s' % (opts.name))
                print >>sys.stdout, _('Stop storage pool. - pool=%s') % (opts.name)
                return True
            except KssCommandException, e:
                raise e
        finally:
            conn.close()
Example #56
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
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug(
                "Get storage pool status failed. Did not validate.")
            return web.badrequest(self.view.alert)

        # Pool
        try:
            kvc = KaresansuiVirtConnection()
            inactive_pool = kvc.list_inactive_storage_pool()
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            self.view.pools = pools

            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                self.logger.debug(
                    "Get storage pool status failed. Target storage pool not found."
                )
                return web.notfound()

            status = STORAGE_POOL_STOP
            if pools_obj[0].is_active() is True:
                status = STORAGE_POOL_START

            if self.__template__["media"] == 'json':
                self.view.status = json_dumps(status)
            else:
                self.view.status = status

            return True
        finally:
            kvc.close()
Example #57
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
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug(
                "Get storage pool info failed. Did not validate.")
            return web.badrequest(self.view.alert)

        try:
            kvc = KaresansuiVirtConnection()
            inactive_pool = kvc.list_inactive_storage_pool()
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            self.view.pools = pools
            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                self.logger.debug(
                    "Get storage pool info failed. Target storage pool not found."
                )
                return web.notfound()

            pool_obj = pools_obj[0]
            pool_info = pool_obj.get_info()
            vols_info = []
            if pool_obj.is_active() is True:
                vols_obj = pool_obj.search_kvn_storage_volumes(kvc)
                for vol_obj in vols_obj:
                    vols_info.append(vol_obj.get_info())

        finally:
            kvc.close()

        self.view.pool_info = pool_info
        self.view.vols_info = vols_info

        return True
Example #58
0
    def _PUT(self, *param, **params):

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

        if is_int(param[2]) is False:
            return web.notfound()       
        nic_id = int(param[2])


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

        model = findbyguest1(self.orm, guest_id)
        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            old_mac = virt.get_interface_info()[nic_id]['mac']['address']
            nic_info = virt.get_interface_info()
        finally:
            kvc.close()

        new_mac = self.input.mac_address

        if old_mac != new_mac:
            f_chk = True
            for x in nic_info:
                if x['mac']['address'] == new_mac:
                    f_chk = False
                    break
            if f_chk is False:
                return web.badrequest(_('Specified MAC address is already defined.'))

            self.logger.debug('spinning off change_mac_job dom=%s, from_mac=%s, to_mac=%s' % (domname, old_mac, new_mac))
            if change_mac_job(self, model, domname, old_mac, new_mac) is True:
                return web.accepted(url=web.ctx.path)
            else:
                return False

        else:
            return web.accepted(url=web.ctx.path)