Example #1
0
    def _GET(self, *param, **params):
        """<comment-ja>
        virDomainState
         - VIR_DOMAIN_NOSTATE = 0
         - VIR_DOMAIN_RUNNING = 1
         - VIR_DOMAIN_BLOCKED = 2
         - VIR_DOMAIN_PAUSED = 3
         - VIR_DOMAIN_SHUTDOWN = 4
         - VIR_DOMAIN_SHUTOFF = 5
         - VIR_DOMAIN_CRASHED = 6
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """

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

        uri_id =  param[1]
        if uri_id is None:
            return web.notfound()

        model = findbyhost1(self.orm, host_id)

        if self.is_mode_input() is False:
            if model.attribute == 2:
                info = {}
                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.kvc = KaresansuiVirtConnectionAuth(uri,creds)

                try:
                    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:
                                info = _v.get_info()
                                if info["uuid"] == uri_id or (uri[0:5] == "test:"):
                                    __guest = MergeGuest(guest.info["model"],_v)
                                    status          = _v.status()
                                    break

                    if self.is_json() is True:
                        self.view.status = json_dumps(status)
                    else:
                        self.view.status = status
                finally:
                    self.kvc.close()

        return True
Example #2
0
    def _GET(self, *param, **params):
        """<comment-ja>
        virDomainState
         - VIR_DOMAIN_NOSTATE = 0
         - VIR_DOMAIN_RUNNING = 1
         - VIR_DOMAIN_BLOCKED = 2
         - VIR_DOMAIN_PAUSED = 3
         - VIR_DOMAIN_SHUTDOWN = 4
         - VIR_DOMAIN_SHUTOFF = 5
         - VIR_DOMAIN_CRASHED = 6
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """

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

        uri_id = param[1]
        if uri_id is None:
            return web.notfound()

        model = findbyhost1(self.orm, host_id)

        if self.is_mode_input() is False:
            if model.attribute == 2:
                info = {}
                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.kvc = KaresansuiVirtConnectionAuth(uri, creds)

                try:
                    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:
                                info = _v.get_info()
                                if info["uuid"] == uri_id or (uri[0:5] == "test:"):
                                    __guest = MergeGuest(guest.info["model"], _v)
                                    status = _v.status()
                                    break

                    if self.is_json() is True:
                        self.view.status = json_dumps(status)
                    else:
                        self.view.status = status
                finally:
                    self.kvc.close()

        return True
Example #3
0
    def _PUT(self, *param, **params):
        """<comment-ja>
        ステータス更新
         - param
           - create = 0
           - shutdown = 1
           - destroy = 2
           - suspend = 3
           - resume = 4
           - reboot = 5
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """

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

        uri_id =  param[1]
        if uri_id is None:
            return web.notfound()

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

        status = int(self.input.status)

        model = findbyhost1(self.orm, host_id)

        if model.attribute == 2:
            info = {}
            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.kvc = KaresansuiVirtConnectionAuth(uri,creds)

            try:
                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:
                            info = _v.get_info()
                            #uri = _v._conn.getURI()
                            if info["uuid"] == uri_id or (uri[0:5] == "test:"):

                                esc_name = "'%s'" % guest.info["model"].name
                                opts = {"name":esc_name,"connection":uri}

                                if creds != '':
                                    passwd_file = KARESANSUI_TMP_DIR + "/" + segs['host'] + ".auth"
                                    open(passwd_file, "w").write(creds)
                                    os.chmod(passwd_file, 0600)
                                    opts["passwd-file"] = passwd_file

                                if status == GUEST_ACTION_CREATE:
                                    # -- Create
                                    cmdname = ["Start Guest", "start guest"]
                                    if _v.is_creatable() is True:
                                        _cmd = dict2command(
                                            "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_START_GUEST),
                                            opts)
                                        
                                        self.view.status = VIRT_COMMAND_START_GUEST
                                    else:
                                        self.logger.error("Create Action:The state can not run. - %d" % _v.status())
                                    
                                elif status == GUEST_ACTION_SHUTDOWN:
                                    cmdname = ["Shutdown Guest", "shutdown guest"]
                                    if _v.is_shutdownable() is True:
                                        # -- Shutdown
                                        _cmd = dict2command(
                                            "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_SHUTDOWN_GUEST),
                                            opts)
                                        
                                        self.view.status = VIRT_COMMAND_SHUTDOWN_GUEST
                                    else:
                                        self.logger.error("Shutdown Action:The state can not run. - %d" % _v.status())
                                
                                elif status == GUEST_ACTION_DESTROY:
                                    cmdname = ["Destroy Guest", "Destroy guest"]
                                    if _v.is_destroyable() is True:
                                        # -- destroy
                                        _cmd = dict2command(
                                            "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_DESTROY_GUEST),
                                            opts)
                                        
                                        self.view.status = VIRT_COMMAND_DESTROY_GUEST
                                    else:
                                        self.logger.error("Destroy Action:The state can not run. - %d" % _v.status())
                                        
                                elif status == GUEST_ACTION_SUSPEND:
                                    cmdname = ["Suspend Guest", "suspend guest"]
                                    if _v.is_suspendable() is True:
                                        # -- Suspend
                                        _cmd = dict2command(
                                            "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_SUSPEND_GUEST),
                                            opts)
                                        
                                        self.view.status = VIRT_COMMAND_SUSPEND_GUEST
                                    else:
                                        self.logger.error("Destroy Action:The state can not run. - %d" % _v.status())
                                        
                                elif status == GUEST_ACTION_RESUME:
                                    cmdname = ["Resume Guest", "resume guest"]
                                    if _v.is_resumable() is True:
                                        # -- Resume
                                        _cmd = dict2command(
                                            "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_RESUME_GUEST),
                                            opts)
                                        
                                        self.view.status = VIRT_COMMAND_RESUME_GUEST
                                    else:
                                        self.logger.error("Resume Action:The state can not run. - %d" % _v.status())
                    
                                elif status == GUEST_ACTION_REBOOT:
                                    cmdname = ["Reboot Guest", "reboot guest"]
                                    if _v.is_shutdownable() is True:
                                        # -- Reboot
                                        _cmd = dict2command(
                                            "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_REBOOT_GUEST),
                                            opts)
                                        
                                        self.view.status = VIRT_COMMAND_REBOOT_GUEST
                                    else:
                                        self.logger.error("Reboot Action:The state can not run. - %d" % _v.status())
                    
                                elif status == GUEST_ACTION_ENABLE_AUTOSTART:
                                    opts["enable"] = None
                                    cmdname = ["Enable Autostart Guest", "enable autostart guest"]
                                    # -- Enable autostart guest
                                    _cmd = dict2command(
                                        "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_AUTOSTART_GUEST),
                                        opts)
                                        
                                    self.view.status = VIRT_COMMAND_AUTOSTART_GUEST
                    
                                elif status == GUEST_ACTION_DISABLE_AUTOSTART:
                                    opts["disable"] = None
                                    cmdname = ["Disable Autostart Guest", "disable autostart guest"]
                                    # -- Disable autostart guest
                                    _cmd = dict2command(
                                        "%s/%s" % (karesansui.config['application.bin.dir'],VIRT_COMMAND_AUTOSTART_GUEST),
                                        opts)
                                        
                                    self.view.status = VIRT_COMMAND_AUTOSTART_GUEST

                                else:
                                    self.logger.error("Action:Bad Request. - request status=%d" % status)
                                    return web.badrequest()

                                break

            finally:
                self.kvc.close()


            # Job Register
            _jobgroup = JobGroup(cmdname[0], karesansui.sheconf['env.uniqkey'])
            _jobgroup.jobs.append(Job('%s command' % cmdname[1], 0, _cmd))
        
            _machine2jobgroup = m2j_new(machine=model,
                                        jobgroup_id=-1,
                                        uniq_key=karesansui.sheconf['env.uniqkey'],
                                        created_user=self.me,
                                        modified_user=self.me,
                                        )

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

            return web.accepted(url="/host/%d/uriguest/%s.part" % (host_id, uri_id))
Example #4
0
    def __init__(self, kvc, model, set_guests=True, if_deleted=2):
        """<comment-ja>
        @param model: Database Model
        @type model: karesansui.db.model.machine.Machine
        @param set_guests: 所属するゲストOS情報を含めるか。
        @type set_guests: bool
        @param is_deleted: 0: すべて, 1: 論理削除のみ, 2: 論理削除以外
        @param is_deleted: int

        注) 本クラスでは、libvirtへのコネクションをクローズしません。呼び出し元でcloseしてください。
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        self.logger = logging.getLogger('karesansui.merge')

        self.info = {"model" : model,
                     "virt" : None,
                     }
        self.guests = []

        self.kvc = kvc
        self.set_guests = set_guests
        self.if_deleted = if_deleted

        if self.set_guests is True:

            if model.attribute == 2:
                #import pdb; pdb.set_trace()
                user  = User(u"unknown",
                             unicode("dummydummy"),
                             unicode("dummydummy"),
                             u"Unknown User",
                             u"",
                            )
                notebook = Notebook(u"", u"")

                for guest_name in kvc.list_active_guest() + kvc.list_inactive_guest():
                    #print guest_name
                    self.logger.info("Reading guest '%s' on '%s' ..." % (guest_name,uri_join(uri_split(model.hostname),without_auth=True)))

                    _virt = kvc.search_kvg_guests(guest_name)
                    if len(_virt) > 0:
                        #uuid = _virt[0].get_info()["uuid"]
                        uuid = _virt[0]._conn.lookupByName(guest_name).UUIDString()

                        #import pdb; pdb.set_trace()
                        guest = Machine(user,
                                        user,
                                        u"%s" % uuid,
                                        u"%s" % guest_name,
                                        MACHINE_ATTRIBUTE['GUEST'],
                                        MACHINE_HYPERVISOR['URI'],
                                        notebook,
                                        [],
                                        u"%s" % "",
                                        u'icon-guest3.png',
                                        False,
                                        None,
                                        )

                        self.guests.append(MergeGuest(guest, _virt[0]))

            else:
                for guest in model.children:
                    if self.if_deleted == 0:
                        _virt = kvc.search_kvg_guests(guest.uniq_key)
                        if len(_virt) > 0:
                            self.guests.append(MergeGuest(guest, _virt[0]))
                    elif self.if_deleted == 1:
                        if guest.is_deleted is True:
                            _virt = kvc.search_kvg_guests(guest.uniq_key)
                            if len(_virt) > 0:
                                self.guests.append(MergeGuest(guest, _virt[0]))
                    elif self.if_deleted == 2:
                        if guest.is_deleted is False:
                            _virt = kvc.search_kvg_guests(guest.uniq_key)
                            if len(_virt) > 0:
                                self.guests.append(MergeGuest(guest, _virt[0]))
                    else:
                        raise Karesansui.KaresansuiLibException("Flag is not expected. if_deleted=%d" % if_deleted)
Example #5
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        if not validates_host_edit(self):
            self.logger.debug("Update Host OS is failed, Invalid input value.")
            return web.badrequest(self.view.alert)

        host = findbyhost1(self.orm, host_id)

        cmp_host = findby1name(self.orm, self.input.m_name)
        if cmp_host is not None and int(host_id) != cmp_host.id:
            self.logger.debug("Update Host OS is failed, "
                              "Already exists name"
                              "- %s, %s" % (host, cmp_host))
            return web.conflict(web.ctx.path)

        if self.input.m_connect_type == "karesansui":
            hostname_check = findby1hostname(self.orm, self.input.m_hostname)
            if hostname_check is not None and int(
                    host_id) != hostname_check.id:
                return web.conflict(web.ctx.path)

        if self.input.m_connect_type == "karesansui":
            host.attribute = MACHINE_ATTRIBUTE['HOST']
            if is_param(self.input, "m_hostname"):
                host.hostname = self.input.m_hostname

        if self.input.m_connect_type == "libvirt":
            host.attribute = MACHINE_ATTRIBUTE['URI']
            if is_param(self.input, "m_uri"):
                segs = uri_split(self.input.m_uri)
                if is_param(self.input,
                            "m_auth_user") and self.input.m_auth_user:
                    segs["user"] = self.input.m_auth_user
                    if is_param(self.input,
                                "m_auth_passwd") and self.input.m_auth_passwd:
                        segs["passwd"] = self.input.m_auth_passwd
                host.hostname = uri_join(segs)

        if is_param(self.input, "note_title"):
            host.notebook.title = self.input.note_title
        if is_param(self.input, "note_value"):
            host.notebook.value = self.input.note_value
        if is_param(self.input, "m_name"):
            host.name = self.input.m_name

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

        # tag UPDATE
        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))
            host.tags = _tags

        host.modified_user = self.me

        m_update(self.orm, host)

        return web.seeother(web.ctx.path)
Example #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
Example #7
0
    def _PUT(self, *param, **params):
        """<comment-ja>
        ステータス更新
         - param
           - create = 0
           - shutdown = 1
           - destroy = 2
           - suspend = 3
           - resume = 4
           - reboot = 5
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """

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

        uri_id = param[1]
        if uri_id is None:
            return web.notfound()

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

        status = int(self.input.status)

        model = findbyhost1(self.orm, host_id)

        if model.attribute == 2:
            info = {}
            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.kvc = KaresansuiVirtConnectionAuth(uri, creds)

            try:
                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:
                            info = _v.get_info()
                            # uri = _v._conn.getURI()
                            if info["uuid"] == uri_id or (uri[0:5] == "test:"):

                                esc_name = "'%s'" % guest.info["model"].name
                                opts = {"name": esc_name, "connection": uri}

                                if creds != "":
                                    passwd_file = KARESANSUI_TMP_DIR + "/" + segs["host"] + ".auth"
                                    open(passwd_file, "w").write(creds)
                                    os.chmod(passwd_file, 0600)
                                    opts["passwd-file"] = passwd_file

                                if status == GUEST_ACTION_CREATE:
                                    # -- Create
                                    cmdname = ["Start Guest", "start guest"]
                                    if _v.is_creatable() is True:
                                        _cmd = dict2command(
                                            "%s/%s"
                                            % (karesansui.config["application.bin.dir"], VIRT_COMMAND_START_GUEST),
                                            opts,
                                        )

                                        self.view.status = VIRT_COMMAND_START_GUEST
                                    else:
                                        self.logger.error("Create Action:The state can not run. - %d" % _v.status())

                                elif status == GUEST_ACTION_SHUTDOWN:
                                    cmdname = ["Shutdown Guest", "shutdown guest"]
                                    if _v.is_shutdownable() is True:
                                        # -- Shutdown
                                        _cmd = dict2command(
                                            "%s/%s"
                                            % (karesansui.config["application.bin.dir"], VIRT_COMMAND_SHUTDOWN_GUEST),
                                            opts,
                                        )

                                        self.view.status = VIRT_COMMAND_SHUTDOWN_GUEST
                                    else:
                                        self.logger.error("Shutdown Action:The state can not run. - %d" % _v.status())

                                elif status == GUEST_ACTION_DESTROY:
                                    cmdname = ["Destroy Guest", "Destroy guest"]
                                    if _v.is_destroyable() is True:
                                        # -- destroy
                                        _cmd = dict2command(
                                            "%s/%s"
                                            % (karesansui.config["application.bin.dir"], VIRT_COMMAND_DESTROY_GUEST),
                                            opts,
                                        )

                                        self.view.status = VIRT_COMMAND_DESTROY_GUEST
                                    else:
                                        self.logger.error("Destroy Action:The state can not run. - %d" % _v.status())

                                elif status == GUEST_ACTION_SUSPEND:
                                    cmdname = ["Suspend Guest", "suspend guest"]
                                    if _v.is_suspendable() is True:
                                        # -- Suspend
                                        _cmd = dict2command(
                                            "%s/%s"
                                            % (karesansui.config["application.bin.dir"], VIRT_COMMAND_SUSPEND_GUEST),
                                            opts,
                                        )

                                        self.view.status = VIRT_COMMAND_SUSPEND_GUEST
                                    else:
                                        self.logger.error("Destroy Action:The state can not run. - %d" % _v.status())

                                elif status == GUEST_ACTION_RESUME:
                                    cmdname = ["Resume Guest", "resume guest"]
                                    if _v.is_resumable() is True:
                                        # -- Resume
                                        _cmd = dict2command(
                                            "%s/%s"
                                            % (karesansui.config["application.bin.dir"], VIRT_COMMAND_RESUME_GUEST),
                                            opts,
                                        )

                                        self.view.status = VIRT_COMMAND_RESUME_GUEST
                                    else:
                                        self.logger.error("Resume Action:The state can not run. - %d" % _v.status())

                                elif status == GUEST_ACTION_REBOOT:
                                    cmdname = ["Reboot Guest", "reboot guest"]
                                    if _v.is_shutdownable() is True:
                                        # -- Reboot
                                        _cmd = dict2command(
                                            "%s/%s"
                                            % (karesansui.config["application.bin.dir"], VIRT_COMMAND_REBOOT_GUEST),
                                            opts,
                                        )

                                        self.view.status = VIRT_COMMAND_REBOOT_GUEST
                                    else:
                                        self.logger.error("Reboot Action:The state can not run. - %d" % _v.status())

                                elif status == GUEST_ACTION_ENABLE_AUTOSTART:
                                    opts["enable"] = None
                                    cmdname = ["Enable Autostart Guest", "enable autostart guest"]
                                    # -- Enable autostart guest
                                    _cmd = dict2command(
                                        "%s/%s"
                                        % (karesansui.config["application.bin.dir"], VIRT_COMMAND_AUTOSTART_GUEST),
                                        opts,
                                    )

                                    self.view.status = VIRT_COMMAND_AUTOSTART_GUEST

                                elif status == GUEST_ACTION_DISABLE_AUTOSTART:
                                    opts["disable"] = None
                                    cmdname = ["Disable Autostart Guest", "disable autostart guest"]
                                    # -- Disable autostart guest
                                    _cmd = dict2command(
                                        "%s/%s"
                                        % (karesansui.config["application.bin.dir"], VIRT_COMMAND_AUTOSTART_GUEST),
                                        opts,
                                    )

                                    self.view.status = VIRT_COMMAND_AUTOSTART_GUEST

                                else:
                                    self.logger.error("Action:Bad Request. - request status=%d" % status)
                                    return web.badrequest()

                                break

            finally:
                self.kvc.close()

            # Job Register
            _jobgroup = JobGroup(cmdname[0], karesansui.sheconf["env.uniqkey"])
            _jobgroup.jobs.append(Job("%s command" % cmdname[1], 0, _cmd))

            _machine2jobgroup = m2j_new(
                machine=model,
                jobgroup_id=-1,
                uniq_key=karesansui.sheconf["env.uniqkey"],
                created_user=self.me,
                modified_user=self.me,
            )

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

            return web.accepted(url="/host/%d/uriguest/%s.part" % (host_id, uri_id))
Example #8
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 =  param[0]
        host_id = self.chk_hostby1(param)
        if host_id is None:
            return web.notfound()

        uri_id =  param[1]
        if uri_id is None:
            return web.notfound()

        model = findbyhost1(self.orm, host_id)

        if self.is_mode_input() is False:
            if model.attribute == 2:
                info = {}
                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.kvc = KaresansuiVirtConnectionAuth(uri,creds)

                try:
                    host = MergeHost(self.kvc, model)
                    for guest in host.guests:
                        if not '__guest' in locals():
                            _virt = self.kvc.search_kvg_guests(guest.info["model"].name)
                            if 0 < len(_virt):
                                for _v in _virt:
                                    info = _v.get_info()
                                    if info["uuid"] == uri_id or (uri[0:5] == "test:"):
                                        __guest = MergeGuest(guest.info["model"],_v)
                                        autostart       = _v.autostart()
                                        status          = _v.status()
                                        is_creatable    = _v.is_creatable()
                                        is_shutdownable = _v.is_shutdownable()
                                        is_suspendable  = _v.is_suspendable()
                                        is_resumable    = _v.is_resumable()
                                        is_destroyable  = _v.is_destroyable()
                                        is_active       = _v.is_active()
                                        break

                    if self.is_json() is True:
                        json_host  = host.get_json(self.me.languages)
                        json_guest = __guest.get_json(self.me.languages)
                        self.view.data = json_dumps(
                            {
                                "parent_model": json_host["model"],
                                "parent_virt": json_host["virt"],
                                "model": json_guest["model"],
                                "virt": json_guest["virt"],
                                "info": info,
                                "autostart": autostart,
                                "status": status,
                                "is_creatable": is_creatable,
                                "is_shutdownable": is_shutdownable,
                                "is_suspendable": is_suspendable,
                                "is_resumable": is_resumable,
                                "is_destroyable": is_destroyable,
                                "is_active": is_active,
                            }
                        )
                    else:
                        self.view.parent_model = host.info["model"]
                        self.view.parent_virt = host.info["virt"]
                        self.view.model = __guest.info["model"]
                        self.view.virt = __guest.info["virt"]
                        self.view.info = info
                        self.view.autostart = autostart
                        self.view.status = status
                        self.view.is_creatable = is_creatable
                        self.view.is_shutdownable = is_shutdownable
                        self.view.is_suspendable = is_suspendable
                        self.view.is_resumable = is_resumable
                        self.view.is_destroyable = is_destroyable
                        self.view.is_active = is_active
                finally:
                    self.kvc.close()

        return True
Example #9
0
    def _POST(self, *param, **params):
        if not validates_host_add(self):
            return web.badrequest(self.view.alert)

        if self.input.m_connect_type == "karesansui":

            uniq_key_check = findby1uniquekey(self.orm, self.input.m_uuid)
            if uniq_key_check is not None and config['application.uniqkey'] != self.input.m_uuid:
                return web.conflict(web.ctx.path)

            hostname_check = findby1hostname(self.orm, self.input.m_hostname)
            if hostname_check is not None:
                return web.conflict(web.ctx.path)

        # 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))

        name = self.input.m_name

        if self.input.m_connect_type == "karesansui":
            uniq_key = self.input.m_uuid
            attribute = MACHINE_ATTRIBUTE['HOST']
            if is_param(self.input, "m_hostname"):
                hostname = self.input.m_hostname

        if self.input.m_connect_type == "libvirt":
            uniq_key = string_from_uuid(generate_uuid())
            attribute = MACHINE_ATTRIBUTE['URI']
            if is_param(self.input, "m_uri"):
                segs = uri_split(self.input.m_uri)
                if is_param(self.input, "m_auth_user") and self.input.m_auth_user:
                    segs["user"] = self.input.m_auth_user
                    if is_param(self.input, "m_auth_passwd") and self.input.m_auth_passwd:
                        segs["passwd"] = self.input.m_auth_passwd
                hostname = uri_join(segs)

        model = findby1uniquekey(self.orm, uniq_key, is_deleted = True)
        if model is None:
            host = m_new(created_user=self.me,
                         modified_user=self.me,
                         uniq_key=uni_force(uniq_key),
                         name=name,
                         hostname=hostname,
                         attribute=attribute,
                         hypervisor=MACHINE_HYPERVISOR['REAL'],
                         notebook=_notebook,
                         tags=_tags,
                         icon=None,
                         is_deleted=False)

            m_save(self.orm, host)
            return web.created(None)
        else:
            model.name = name
            model.hostname = hostname
            model.uniq_key = uniq_key
            model.notebook.title = note_title
            model.notebook.value = note_value
            model.tags = _tags
            model.is_deleted = False
            m_update(self.orm, model)
            return web.created(None)
Example #10
0
    def __init__(self, kvc, model, set_guests=True, if_deleted=2):
        """<comment-ja>
        @param model: Database Model
        @type model: karesansui.db.model.machine.Machine
        @param set_guests: 所属するゲストOS情報を含めるか。
        @type set_guests: bool
        @param is_deleted: 0: すべて, 1: 論理削除のみ, 2: 論理削除以外
        @param is_deleted: int

        注) 本クラスでは、libvirtへのコネクションをクローズしません。呼び出し元でcloseしてください。
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        self.logger = logging.getLogger('karesansui.merge')

        self.info = {
            "model": model,
            "virt": None,
        }
        self.guests = []

        self.kvc = kvc
        self.set_guests = set_guests
        self.if_deleted = if_deleted

        if self.set_guests is True:

            if model.attribute == 2:
                #import pdb; pdb.set_trace()
                user = User(
                    u"unknown",
                    unicode("dummydummy"),
                    unicode("dummydummy"),
                    u"Unknown User",
                    u"",
                )
                notebook = Notebook(u"", u"")

                for guest_name in kvc.list_active_guest(
                ) + kvc.list_inactive_guest():
                    #print guest_name
                    self.logger.info("Reading guest '%s' on '%s' ..." %
                                     (guest_name,
                                      uri_join(uri_split(model.hostname),
                                               without_auth=True)))

                    _virt = kvc.search_kvg_guests(guest_name)
                    if len(_virt) > 0:
                        #uuid = _virt[0].get_info()["uuid"]
                        uuid = _virt[0]._conn.lookupByName(
                            guest_name).UUIDString()

                        #import pdb; pdb.set_trace()
                        guest = Machine(
                            user,
                            user,
                            u"%s" % uuid,
                            u"%s" % guest_name,
                            MACHINE_ATTRIBUTE['GUEST'],
                            MACHINE_HYPERVISOR['URI'],
                            notebook,
                            [],
                            u"%s" % "",
                            u'icon-guest3.png',
                            False,
                            None,
                        )

                        self.guests.append(MergeGuest(guest, _virt[0]))

            else:
                for guest in model.children:
                    if self.if_deleted == 0:
                        _virt = kvc.search_kvg_guests(guest.uniq_key)
                        if len(_virt) > 0:
                            self.guests.append(MergeGuest(guest, _virt[0]))
                    elif self.if_deleted == 1:
                        if guest.is_deleted is True:
                            _virt = kvc.search_kvg_guests(guest.uniq_key)
                            if len(_virt) > 0:
                                self.guests.append(MergeGuest(guest, _virt[0]))
                    elif self.if_deleted == 2:
                        if guest.is_deleted is False:
                            _virt = kvc.search_kvg_guests(guest.uniq_key)
                            if len(_virt) > 0:
                                self.guests.append(MergeGuest(guest, _virt[0]))
                    else:
                        raise Karesansui.KaresansuiLibException(
                            "Flag is not expected. if_deleted=%d" % if_deleted)
Example #11
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 == 2:
            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
        finally:
            #self.kvc.close()
            pass # libvirt connection scope --> Guest#_post()
Example #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()
Example #13
0
class RebootGuest(KssCommand):
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        passwd = None
        if 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.- dom=%s passwd_file=%s' \
                      % (opts.name,opts.passwd_file))
                print >>sys.stderr,_('Failed to read.- dom=%s passwd_file=%s') \
                      % (opts.name,opts.passwd_file)
                raise e

            os.remove(opts.passwd_file)

        try:
            if passwd is None:
                if opts.uri is None:
                    conn = KaresansuiVirtConnection(readonly=False)
                else:
                    uri = uri_join(uri_split(opts.uri), without_auth=True)
                    conn = KaresansuiVirtConnection(uri, readonly=False)

            else:
                if opts.uri is None:
                    conn = KaresansuiVirtConnectionAuth(creds=passwd,
                                                        readonly=False)
                else:
                    uri = uri_join(uri_split(opts.uri), without_auth=True)
                    conn = KaresansuiVirtConnectionAuth(uri,
                                                        creds=passwd,
                                                        readonly=False)

            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.reboot_guest()
                    self.up_progress(30)
                except Exception, e:
                    self.logger.error('Failed to reboot guest. - dom=%s' %
                                      (opts.name))
                    print >> sys.stderr, _(
                        'Failed to reboot guest. - dom=%s') % (opts.name)
                    raise e

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

            else:
Example #14
0
class AutostartGuest(KssCommand):
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        passwd = None
        if 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.- dom=%s passwd_file=%s' \
                      % (opts.name,opts.passwd_file))
                print >>sys.stderr,_('Failed to read.- dom=%s passwd_file=%s') \
                      % (opts.name,opts.passwd_file)
                raise e

            os.remove(opts.passwd_file)

        try:
            if passwd is None:
                if opts.uri is None:
                    conn = KaresansuiVirtConnection(readonly=False)
                else:
                    uri = uri_join(uri_split(opts.uri), without_auth=True)
                    conn = KaresansuiVirtConnection(uri, readonly=False)

            else:
                if opts.uri is None:
                    conn = KaresansuiVirtConnectionAuth(creds=passwd,
                                                        readonly=False)
                else:
                    uri = uri_join(uri_split(opts.uri), without_auth=True)
                    conn = KaresansuiVirtConnectionAuth(uri,
                                                        creds=passwd,
                                                        readonly=False)

            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)

        except Exception, e:

            if flag is True:
                self.logger.error(
                    'Failed to configure a domain to be automatically started at boot. - dom=%s'
                    % (opts.name))
                print >> sys.stderr, _(
                    'Failed to configure a domain to be automatically started at boot. - dom=%s'
                ) % (opts.name)
            else:
                self.logger.error(
                    'Failed to configure a domain not to be automatically started at boot. - dom=%s'
                    % (opts.name))
                print >> sys.stderr, _(
                    'Failed to configure a domain not to be automatically started at boot. - dom=%s'
                ) % (opts.name)

            raise e