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

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

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

        guest = m_findbyguest1(self.orm, guest_id)
        if not guest:
            return web.notfound()

        snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
        if not snapshot:
            notebook = new_notebook(self.input.title, self.input.value)
            snapshot = new_snapshot(guest, int(snapshot_id), self.me, self.me, notebook)
            save_snapshot(self.orm, snapshot)
        else:
            snapshot.notebook.title = self.input.title
            snapshot.notebook.value = self.input.value

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

        guest = findbyguest1(self.orm, guest_id)

        kvs = KaresansuiVirtSnapshot(readonly=False)
        try:
            domname = kvs.kvc.uuid_to_domname(guest.uniq_key)
            if not domname: return web.notfound()

            if self.is_mode_input():
                virt = kvs.kvc.search_kvg_guests(domname)[0]
                if virt.is_active() is True:
                    return web.badrequest(_("Guest is running. Please stop and try again. name=%s" % domname))

            self.view.is_creatable = kvs.isSupportedDomain(domname)

            self.view.snapshot_error_msg = ''
            if self.view.is_creatable is not True and len(kvs.error_msg) > 0:
                self.view.snapshot_error_msg = ", ".join(kvs.error_msg)

            try:
                snapshot_list = kvs.listNames(domname)[domname]
            except:
                pass

            current_snapshot = kvs.getCurrentSnapshotName(domname)

        finally:
            kvs.finish()

        snapshots = []
        if snapshot_list:
            snapshot_list.sort(reverse = True)
            for snapshot in snapshot_list:
                model = s_findbyname_guestby1(self.orm, snapshot,guest_id)
                if model is None:
                    name           = snapshot
                    notebook_title = ""
                    created_user   = _("N/A")
                    created        = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(snapshot)))
                else:
                    name           = model.name
                    notebook_title = model.notebook.title
                    created_user   = model.created_user.nickname
                    created        = model.created

                current = False
                if snapshot == current_snapshot:
                    current = True

                snapshots.append((name,
                                  notebook_title,
                                  domname,
                                  created_user,
                                  created,
                                  current
                                  ))

        self.view.snapshots = snapshots
        self.view.guest = guest
            
        return True
    def _PUT(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        if is_param(self.input, 'id') is False \
            or is_int(self.input.id) is False:
            return web.badrequest("Request data is invalid.")

        snapshot_id = str(self.input.id)

        snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
        if snapshot is None:
            pass
            # ignore snapshots that is not in database.
            #return web.badrequest("Request data is invalid.")

        model = findbyguest1(self.orm, guest_id)

        kvs = KaresansuiVirtSnapshot(readonly=False)
        snapshot_list = []
        try:
            domname = kvs.kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.notfound()
            self.view.is_creatable = kvs.isSupportedDomain(domname)
            try:
                snapshot_list = kvs.listNames(domname)[domname]
            except:
                pass

        finally:
            kvs.finish()

        if not snapshot_id in snapshot_list:
            self.logger.debug(_("The specified snapshot does not exist in database. - %s") % snapshot_id)
            # ignore snapshots that is not in database.
            #return web.notfound()

        action_cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'],
                       VIRT_COMMAND_APPLY_SNAPSHOT),
            {"name" : domname, "id" : snapshot_id})

        cmdname = 'Apply Snapshot'

        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _job = Job('%s command' % cmdname, 0, action_cmd)
        _jobgroup.jobs.append(_job)

        _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,
                               )        

        self.view.currentsnapshot = snapshot

        return web.accepted(url=web.ctx.path)
Example #4
0
    def _GET(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()
        
        snapshot_id = param[2]
        if not validates_param_id(self, snapshot_id):
            return web.notfound(self.view.alert)

        guest = m_findbyguest1(self.orm, guest_id)
        if not guest:
            return web.notfound()

        kvs = KaresansuiVirtSnapshot(readonly=False)
        snapshot_list = []
        try:
            domname = kvs.kvc.uuid_to_domname(guest.uniq_key)
            if not domname: return web.notfound()
            self.view.is_creatable = kvs.isSupportedDomain(domname)
            try:
                snapshot_list = kvs.listNames(domname)[domname]
            except:
                pass

            parent_name  = kvs.getParentName(snapshot_id,domain=domname)
            if parent_name is None:
                parent_name = _('None')
            children_names = kvs.getChildrenNames(snapshot_id,domain=domname)
            if len(children_names) == 0:
                children_name = _('None')
            else:
                children_name = ",".join(children_names)

            model = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
            if model is None:
                name           = snapshot_id
                notebook_title = ""
                notebook_value = ""
                created_user   = _("N/A")
                created        = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(snapshot_id)))
                modified_user  = _("N/A")
                modified       = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(snapshot_id)))
            else:
                name           = model.name
                notebook_title = model.notebook.title
                notebook_value = model.notebook.value
                created_user   = model.created_user.nickname
                created        = model.created
                modified_user  = model.modified_user.nickname
                modified       = model.modified

            current_snapshot = kvs.getCurrentSnapshotName(domname)

            current = False
            if snapshot_id == current_snapshot:
                current = True

        finally:
            kvs.finish()

        if not snapshot_id in snapshot_list:
            self.logger.error(_("The specified snapshot does not exist. - %s") % snapshot_id)
            return web.notfound()

        if self.__template__["media"] == 'json':
            self.view.snapshot = json_dumps((
                                  snapshot_id,
                                  notebook_title,
                                  notebook_value,
                                  domname,
                                  created_user,
                                  created,
                                  modified_user,
                                  modified,
                                  current,
                                  parent_name,
                                  children_name,
                                 ))
        else:
            self.view.snapshot = (snapshot_id,
                                  notebook_title,
                                  notebook_value,
                                  domname,
                                  created_user,
                                  created,
                                  modified_user,
                                  modified,
                                  current,
                                  parent_name,
                                  children_name,
                                  )
        return True
Example #5
0
    def _DELETE(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

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

        guest = m_findbyguest1(self.orm, guest_id)
        if not guest:
            return web.notfound()

        kvs = KaresansuiVirtSnapshot(readonly=False)
        snapshot_list = []
        try:
            domname = kvs.kvc.uuid_to_domname(guest.uniq_key)
            if not domname: return web.notfound()
            self.view.is_creatable = kvs.isSupportedDomain(domname)
            try:
                snapshot_list = kvs.listNames(domname)[domname]
            except:
                pass

            current_snapshot = kvs.getCurrentSnapshotName(domname)

        finally:
            kvs.finish()

        if not snapshot_id in snapshot_list:
            self.logger.error(_("The specified snapshot does not exist. - %s") % snapshot_id)
            return web.notfound()

        # delete
        action_cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'],
                       VIRT_COMMAND_DELETE_SNAPSHOT),
            {"name" : domname, "id" : snapshot_id})

        cmdname = 'Delete Snapshot'
        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _job = Job('%s command' % cmdname, 0, action_cmd)
        _jobgroup.jobs.append(_job)
        
        _machine2jobgroup = m2j_new(machine=guest,
                                    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,
                               )        

        snapshot = s_findbyname_guestby1(self.orm, snapshot_id, guest_id)
        if snapshot:
            logical_delete(self.orm, snapshot)

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

        conn = KaresansuiVirtConnection(readonly=False)
        try:
            try:
                src_pool = conn.get_storage_pool_name_bydomain(opts.name, "os")
                if not src_pool:
                    raise KssCommandException("Source storage pool not found. domain=%s" % (opts.name))
                if conn.get_storage_pool_type(src_pool) == 'dir':
                    raise KssCommandException("Storage pool type 'dir' is not. domain=%s" % (opts.name))

                src_path = conn.get_storage_pool_targetpath(src_pool[0])
                self.domain_dir  = "%s/%s" % (src_path, opts.name,)

                if os.path.isdir(self.domain_dir) is False:
                    raise KssCommandException(
                        'domain directory is not found or not directory. - %s' % (self.domain_dir))

                # Model
                virt_uuid = conn.domname_to_uuid(opts.name)
                model = findby1uniquekey(self.kss_session, virt_uuid)
                if not model:
                    raise KssCommandException("Export data does not exist in the database.")

                database = {}
                database['attribute'] = model.attribute
                database['hypervisor'] = model.hypervisor
                database['icon'] = model.icon
                database['name'] = model.name
                database['notebook'] = {"title" : model.notebook.title,
                                        "value" : model.notebook.value,
                                        }
                tags = []
                for _tag in model.tags:
                    tags.append(_tag.name)

                database['tags'] = ",".join(tags)
                database['uniq_key'] = model.uniq_key

                # Snapshot
                snapshots = []
                kvs = KaresansuiVirtSnapshot(readonly=False)
                try:
                    guest_id = model.id
                    snapshot_list = kvs.listNames(opts.name)[opts.name]
                    if len(snapshot_list) > 0:
                        for snapshot in snapshot_list:
                            s_model = s_findbyname_guestby1(self.kss_session, snapshot, guest_id)
                            if s_model is not None:
                                name  = s_model.name
                                title = s_model.notebook.title
                                value = s_model.notebook.value
                                snapshots.append({"name":name, "title":title, "value":value,})
                except:
                    raise KssCommandException("Cannot fetch the information of snapshots correctly.")
                kvs.finish()

                # Pool
                target_dir = ""
                if opts.pool:
                    inactive_storage_pools = conn.list_inactive_storage_pool()
                    active_storage_pools = conn.list_active_storage_pool()
                    if not (opts.pool in active_storage_pools or opts.pool in inactive_storage_pools):
                        raise KssCommandException('Target storage pool does not exist. - pool=%s' % (opts.pool))

                    pool = conn.search_kvn_storage_pools(opts.pool)
                    storage_info = pool[0].get_info()
                    if storage_info["type"] == "dir" and storage_info["target"]["path"] != "":
                        target_dir = storage_info["target"]["path"]
                    else:
                        raise KssCommandException("Target storage pool type is not 'dir'. pool=%s" % (opts.pool))
                elif opts.dir:
                    target_dir = opts.dir

                self.up_progress(10)
                progresscb = None
                if opts.verbose:
                    try:
                        from karesansui.lib.progress import ProgressMeter
                        progresscb = ProgressMeter(command_object=self)
                    except:
                        pass
                else:
                    try:
                        from karesansui.lib.progress import ProgressMeter
                        progresscb = ProgressMeter(command_object=self,quiet=True)
                    except:
                        pass

                if opts.title[0:4] == "b64:":
                    title = base64_decode(opts.title[4:])
                else:
                    title = opts.title

                uuid = StrFromUUID(GenUUID())
                conn.export_guest(uuid=uuid,
                                  name=opts.name,
                                  directory=target_dir,
                                  database=database,
                                  realicon=model.realicon(),
                                  title=title,
                                  snapshots=snapshots,
                                  progresscb=progresscb)

                self.up_progress(40)
                self.logger.info('Export guest completed. - pool=%s, uuid=%s' % (opts.pool, uuid))
                print >>sys.stdout, _('Export guest completed. - pool=%s, uuid=%s' % (opts.pool, uuid))
                return True

            except KaresansuiVirtException, e:
                raise KssCommandException('Failed to export guest. - %s to %s [%s]' \
                                          % (opts.name,target_dir, ''.join(e.args)))

            except KssCommandException:
                raise

            except:
                raise KssCommandException('Failed to export guest. - %s to %s' \
                                          % (opts.name,target_dir))