示例#1
0
    def isSupportedDomain(self, domain=None):
        retval = True

        inactives = self.kvc.list_inactive_guest()
        actives = self.kvc.list_active_guest()

        if domain is not None:
            if domain in inactives + actives:
                guest = self.kvc.search_guests(domain)[0]

                param = ConfigParam(domain)
                param.load_xml_config(guest.XMLDesc(1))

                for info in param.disks:
                    """
                    { 'bus'        :'ide',
                      'device'     :'disk',
                      'disk_type'  :'file',
                      'driver_name':'qemu',
                      'driver_type':'qcow2',
                      'path'       :'/path/to/disk_image.img',
                      'target'     :'hda'}
                    """
                    try:
                        if info['driver_type'] == "qcow2":
                            pass
                        elif info['device'] == "cdrom":
                            pass
                        else:
                            if info['disk_type'] != "block":
                                self.append_error_msg(
                                    _("%s: unsupported image format %s") %
                                    (info['target'], info['driver_type']))
                                retval = False
                                #break
                    except:
                        retval = False
                        #break
            else:
                retval = False

        return retval
示例#2
0
    def isSupportedDomain(self,domain=None):
        retval = True

        inactives = self.kvc.list_inactive_guest()
        actives   = self.kvc.list_active_guest()

        if domain is not None:
            if domain in inactives + actives:
                guest = self.kvc.search_guests(domain)[0]

                param = ConfigParam(domain)
                param.load_xml_config(guest.XMLDesc(1))

                for info in param.disks:
                    """
                    { 'bus'        :'ide',
                      'device'     :'disk',
                      'disk_type'  :'file',
                      'driver_name':'qemu',
                      'driver_type':'qcow2',
                      'path'       :'/path/to/disk_image.img',
                      'target'     :'hda'}
                    """
                    try:
                        if info['driver_type'] == "qcow2":
                            pass
                        elif info['device'] == "cdrom":
                            pass
                        else:
                            if info['disk_type'] != "block":
                                self.append_error_msg(_("%s: unsupported image format %s") % (info['target'],info['driver_type']))
                                retval = False
                                #break
                    except:
                        retval = False
                        #break
            else:
                retval = False

        return retval
示例#3
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        kvc = KaresansuiVirtConnection()
        # #1 libvirt process
        try:
            # inactive_pool = kvc.list_inactive_storage_pool()
            inactive_pool = []
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            export = []
            for pool_name in pools:
                pool = 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,)):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != opts.uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            raise KssCommandException("Export corrupt data.(file not found) - path=%s" % path)

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            raise KssCommandException(
                                "Export corrupt data.(The name does not match) - info=%s, xml=%s"
                                % (e_name, param.get_name())
                            )

                        _dir = os.path.dirname(_afile)

                        export.append({"dir": _dir, "pool": pool_name, "uuid": e_param.get_uuid(), "name": e_name})

            if len(export) < 1:
                # refresh pool.
                conn = KaresansuiVirtConnection(readonly=False)
                try:
                    conn.refresh_pools()
                finally:
                    conn.close()
                raise KssCommandException("libvirt data did not exist. - uuid=%s" % opts.uuid)
            else:
                export = export[0]

        finally:
            kvc.close()

        self.up_progress(30)
        # #2 physical process
        if os.path.isdir(export["dir"]) is False:
            raise KssCommandException(
                _("Failed to delete export data. - %s") % (_("Export data directory not found. [%s]") % (export["dir"]))
            )

        uuid = os.path.basename(export["dir"])
        pool_dir = os.path.dirname(export["dir"])

        if not is_uuid(export["uuid"]):
            raise KssCommandException(
                _("Failed to delete export data. - %s")
                % (_("'%s' is not valid export data directory.") % (export["dir"]))
            )

        shutil.rmtree(export["dir"])

        for _afile in glob.glob("%s*img" % (export["dir"])):
            os.remove(_afile)

        self.up_progress(30)
        # refresh pool.
        conn = KaresansuiVirtConnection(readonly=False)
        try:
            try:
                conn.refresh_pools()
            finally:
                conn.close()
        except:
            pass

        self.logger.info("Deleted export data. - uuid=%s" % (opts.uuid))
        print >>sys.stdout, _("Deleted export data. - uuid=%s") % (opts.uuid)
        return True
示例#4
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # valid
        self.view.uuid = param[1]

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

            export = []
            for pool_name in pools:
                pool = 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,)):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != self.view.uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error('Export corrupt data.(file not found) - path=%s' % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        export.append({"dir" : _dir,
                                       "pool" : pool_name,
                                       "uuid" : e_param.get_uuid(),
                                       "name" : e_name,
                                       })

            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" % self.view.uuid)
                return web.badrequest()
        finally:
            kvc.close()

        export = export[0]
        if os.path.exists(export['dir']) is False or os.path.isdir(export['dir']) is False:
            self.logger.error('Export data is not valid. [%s]' % export_dir)
            return web.badrequest('Export data is not valid.')

        host = findbyhost1(self.orm, host_id)

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

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

        # Job Registration
        _jobgroup = JobGroup('Delete Export Data', karesansui.sheconf['env.uniqkey'])

        _jobgroup.jobs.append(Job('Delete Export Data', 0, _cmd))

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

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

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

        return web.accepted()
示例#5
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # valid
        self.view.uuid = param[1]

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

            export = []
            for pool_name in pools:
                pool = 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,)):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != self.view.uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error('Export corrupt data.(file not found) - path=%s' % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        title = e_param.get_title()
                        if title != "":
                            title = re.sub("[\r\n]","",title)
                        if title == "":
                            title = _('untitled')

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

                        export.append({"info" : {"dir" : _dir,
                                                 "pool" : pool_name,
                                                 "uuid" : e_param.get_uuid(),
                                                 "name" : e_name,
                                                 "created" : int(created),
                                                 "created_str" : created_str,
                                                 "title" : title,
                                                  },
                                       "xml" : {"on_reboot" : param.get_behavior('on_reboot'),
                                                "on_poweroff" : param.get_behavior('on_poweroff'),
                                                "on_crash" : param.get_behavior('on_crash'),
                                                "boot_dev" : param.get_boot_dev(),
                                                #"bootloader" : param.get_bootloader(),
                                                #"commandline" : param.get_commandline(),
                                                #"current_snapshot" : param.get_current_snapshot(),
                                                'disk' : param.get_disk(),
                                                "domain_name" : param.get_domain_name(),
                                                "domain_type" : param.get_domain_type(),
                                                "features_acpi" : param.get_features_acpi(),
                                                "features_apic" : param.get_features_apic(),
                                                "features_pae" : param.get_features_pae(),
                                                #"initrd" : param.get_initrd(),
                                                "interface" : param.get_interface(),
                                                #"kernel" : param.get_kernel(),
                                                "max_memory" : param.get_max_memory(),
                                                'max_vcpus' : param.get_max_vcpus(),
                                                "max_vcpus_limit" : param.get_max_vcpus_limit(),
                                                "memory" : param.get_memory(),
                                                "uuid" : param.get_uuid(),
                                                "vcpus" : param.get_vcpus(),
                                                "vcpus_limit" : param.get_vcpus_limit(),
                                                "vnc_autoport" : param.get_vnc_autoport(),
                                                "keymap" : param.get_vnc_keymap(),
                                                "vnc_listen" : param.get_vnc_listen(),
                                                "vnc_passwd" : param.get_vnc_passwd(),
                                                "vnc_port" : param.get_vnc_port(),
                                                },
                                       "pool" : pool[0].get_info(),
                                       })

            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" % self.view.uuid)
                return web.badrequest()

            # .json
            if self.is_json() is True:
                self.view.export = json_dumps(export[0])
            else:
                self.view.export = export

            return True
        finally:
            kvc.close() 
示例#6
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # valid
        self.view.uuid = param[1]

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

            export = []
            for pool_name in pools:
                pool = 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, )):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != self.view.uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error(
                                'Export corrupt data.(file not found) - path=%s'
                                % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        title = e_param.get_title()
                        if title != "":
                            title = re.sub("[\r\n]", "", title)
                        if title == "":
                            title = _('untitled')

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

                        export.append({
                            "info": {
                                "dir": _dir,
                                "pool": pool_name,
                                "uuid": e_param.get_uuid(),
                                "name": e_name,
                                "created": int(created),
                                "created_str": created_str,
                                "title": title,
                            },
                            "xml": {
                                "on_reboot": param.get_behavior('on_reboot'),
                                "on_poweroff":
                                param.get_behavior('on_poweroff'),
                                "on_crash": param.get_behavior('on_crash'),
                                "boot_dev": param.get_boot_dev(),
                                #"bootloader" : param.get_bootloader(),
                                #"commandline" : param.get_commandline(),
                                #"current_snapshot" : param.get_current_snapshot(),
                                'disk': param.get_disk(),
                                "domain_name": param.get_domain_name(),
                                "domain_type": param.get_domain_type(),
                                "features_acpi": param.get_features_acpi(),
                                "features_apic": param.get_features_apic(),
                                "features_pae": param.get_features_pae(),
                                #"initrd" : param.get_initrd(),
                                "interface": param.get_interface(),
                                #"kernel" : param.get_kernel(),
                                "max_memory": param.get_max_memory(),
                                'max_vcpus': param.get_max_vcpus(),
                                "max_vcpus_limit": param.get_max_vcpus_limit(),
                                "memory": param.get_memory(),
                                "uuid": param.get_uuid(),
                                "vcpus": param.get_vcpus(),
                                "vcpus_limit": param.get_vcpus_limit(),
                                "graphics_autoport":
                                param.get_graphics_autoport(),
                                "keymap": param.get_graphics_keymap(),
                                "graphics_listen": param.get_graphics_listen(),
                                "graphics_passwd": param.get_graphics_passwd(),
                                "graphics_port": param.get_graphics_port(),
                            },
                            "pool": pool[0].get_info(),
                        })

            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" %
                                 self.view.uuid)
                return web.badrequest()

            # .json
            if self.is_json() is True:
                self.view.export = json_dumps(export[0])
            else:
                self.view.export = export

            return True
        finally:
            kvc.close()
示例#7
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # valid
        self.view.uuid = param[1]

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

            export = []
            for pool_name in pools:
                pool = 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, )):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != self.view.uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error(
                                'Export corrupt data.(file not found) - path=%s'
                                % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        export.append({
                            "dir": _dir,
                            "pool": pool_name,
                            "uuid": e_param.get_uuid(),
                            "name": e_name,
                        })

            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" %
                                 self.view.uuid)
                return web.badrequest()
        finally:
            kvc.close()

        export = export[0]
        if os.path.exists(export['dir']) is False or os.path.isdir(
                export['dir']) is False:
            self.logger.error('Export data is not valid. [%s]' % export_dir)
            return web.badrequest('Export data is not valid.')

        host = findbyhost1(self.orm, host_id)

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

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

        # Job Registration
        _jobgroup = JobGroup('Delete Export Data',
                             karesansui.sheconf['env.uniqkey'])

        _jobgroup.jobs.append(Job('Delete Export Data', 0, _cmd))

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

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

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

        return web.accepted()
示例#8
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

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

        uuid = self.input.uuid
        kvc = KaresansuiVirtConnection()
        try:
            # Storage Pool
            #inactive_pool = kvc.list_inactive_storage_pool()
            inactive_pool = []
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            export = []
            for pool_name in pools:
                pool = 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,)):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error('Export corrupt data.(file not found) - path=%s' % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        title = e_param.get_title()
                        if title != "":
                            title = re.sub("[\r\n]","",title)
                        if title == "":
                            title = _('untitled')

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

                        export.append({"info" : {"dir" : _dir,
                                                 "pool" : pool_name,
                                                 "uuid" : e_param.get_uuid(),
                                                 "name" : e_param.get_domain(),
                                                 "created" : int(created),
                                                 "created_str" : created_str,
                                                 "title" : title,
                                                 "database" : {"name" : e_param.database["name"],
                                                               "tags" : e_param.database["tags"],
                                                               "attribute" : e_param.database["attribute"],
                                                               "notebook" : {"title" : e_param.database["notebook"]["title"],
                                                                             "value" : e_param.database["notebook"]["value"],
                                                                             },
                                                               "uniq_key" : e_param.database["uniq_key"],
                                                               "hypervisor" : e_param.database["hypervisor"],
                                                               "icon" : e_param.database["icon"],
                                                               },
                                                  },
                                       "xml" : {"on_reboot" : param.get_behavior('on_reboot'),
                                                "on_poweroff" : param.get_behavior('on_poweroff'),
                                                "on_crash" : param.get_behavior('on_crash'),
                                                "boot_dev" : param.get_boot_dev(),
                                                #"bootloader" : param.get_bootloader(),
                                                #"commandline" : param.get_commandline(),
                                                #"current_snapshot" : param.get_current_snapshot(),
                                                'disk' : param.get_disk(),
                                                "domain_name" : param.get_domain_name(),
                                                "domain_type" : param.get_domain_type(),
                                                "features_acpi" : param.get_features_acpi(),
                                                "features_apic" : param.get_features_apic(),
                                                "features_pae" : param.get_features_pae(),
                                                #"initrd" : param.get_initrd(),
                                                "interface" : param.get_interface(),
                                                #"kernel" : param.get_kernel(),
                                                "max_memory" : param.get_max_memory(),
                                                'max_vcpus' : param.get_max_vcpus(),
                                                "max_vcpus_limit" : param.get_max_vcpus_limit(),
                                                "memory" : param.get_memory(),
                                                "uuid" : param.get_uuid(),
                                                "vcpus" : param.get_vcpus(),
                                                "vcpus_limit" : param.get_vcpus_limit(),
                                                "vnc_autoport" : param.get_vnc_autoport(),
                                                "keymap" : param.get_vnc_keymap(),
                                                "vnc_listen" : param.get_vnc_listen(),
                                                "vnc_passwd" : param.get_vnc_passwd(),
                                                "vnc_port" : param.get_vnc_port(),
                                                },
                                       "pool" : pool[0].get_info(),
                                       })
            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" % self.view.uuid)
                return web.badrequest()
            else:
                export = export[0]
        finally:
            kvc.close()

        # Pool running?
        if export['pool']['is_active'] is False:
            return web.badrequest("The destination, the storage pool is not running.")

        dest_domname = export['xml']['domain_name']
        dest_uniqkey = export['info']['database']['uniq_key']
        # Same guest OS is already running.
        if m_findby1uniquekey(self.orm, dest_uniqkey) is not None:
            self.logger.info(_("guest '%s' already exists. (DB) - %s") % (dest_domname, dest_uniqkey))
            return web.badrequest(_("guest '%s' already exists.") % dest_domname)

        dest_dir = "%s/%s" % (export['pool']['target']['path'], export['xml']['domain_name'])
        if os.path.exists(dest_dir) is True:
            self.logger.info(_("guest '%s' already exists. (FS) - %s") % (dest_domname, dest_dir))
            return  web.badrequest(_("guest '%s' already exists.") % dest_domname)

        # disk check
        try:
            src_disk = "%s/%s/images/%s.img" \
                       % (export["info"]["dir"], export["info"]["name"], export["info"]["name"])

            if os.path.exists(src_disk):
                s_size = os.path.getsize(src_disk) / (1024 * 1024) # a unit 'MB'
                if chk_create_disk(export["info"]["dir"], s_size) is False:
                    partition = get_partition_info(export["info"]["dir"], header=False)
                    return web.badrequest(
                        _("No space available to create disk image in '%s' partition.") \
                        % partition[5][0])
        except:
            pass

        extra_uniq_key = string_from_uuid(generate_uuid())
        options = {}
        options["exportuuid"] = export["info"]["uuid"]
        options["destuuid"] = extra_uniq_key
        options["quiet"] = None

        # Database Notebook
        try:
            _notebook = n_new(
                export["info"]["database"]["notebook"]["title"],
                export["info"]["database"]["notebook"]["value"],
                )
        except:
            _notebook = None

        # Database Tag
        _tags = []
        try:
            tag_array = comma_split(export["info"]["database"]["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))
        except:
            _tags.append(t_new(""))

        parent = m_findby1(self.orm, host_id)
        dest_guest = m_new(created_user=self.me,
                           modified_user=self.me,
                           uniq_key=extra_uniq_key,
                           name=export["info"]["database"]["name"],
                           attribute=int(export["info"]["database"]["attribute"]),
                           hypervisor=int(export["info"]["database"]["hypervisor"]),
                           notebook=_notebook,
                           tags=_tags,
                           icon=export["info"]["database"]["icon"],
                           is_deleted=False,
                           parent=parent,
                           )

        ret = regist_guest(self,
                           _guest=dest_guest,
                           icon_filename=export["info"]["database"]["icon"],
                           cmd=VIRT_COMMAND_IMPORT_GUEST,
                           options=options,
                           cmdname=['Import Guest', 'Import Guest'],
                           rollback_options={"name" : export["xml"]["domain_name"]},
                           is_create=False
                           )

        if ret is True:
            return web.accepted()
        else:
            return False
示例#9
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

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

        uuid = self.input.uuid
        kvc = KaresansuiVirtConnection()
        try:
            # Storage Pool
            #inactive_pool = kvc.list_inactive_storage_pool()
            inactive_pool = []
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            export = []
            for pool_name in pools:
                pool = 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, )):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error(
                                'Export corrupt data.(file not found) - path=%s'
                                % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        title = e_param.get_title()
                        if title != "":
                            title = re.sub("[\r\n]", "", title)
                        if title == "":
                            title = _('untitled')

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

                        export.append({
                            "info": {
                                "dir": _dir,
                                "pool": pool_name,
                                "uuid": e_param.get_uuid(),
                                "name": e_param.get_domain(),
                                "created": int(created),
                                "created_str": created_str,
                                "title": title,
                                "database": {
                                    "name": e_param.database["name"],
                                    "tags": e_param.database["tags"],
                                    "attribute": e_param.database["attribute"],
                                    "notebook": {
                                        "title":
                                        e_param.database["notebook"]["title"],
                                        "value":
                                        e_param.database["notebook"]["value"],
                                    },
                                    "uniq_key": e_param.database["uniq_key"],
                                    "hypervisor":
                                    e_param.database["hypervisor"],
                                    "icon": e_param.database["icon"],
                                },
                            },
                            "xml": {
                                "on_reboot": param.get_behavior('on_reboot'),
                                "on_poweroff":
                                param.get_behavior('on_poweroff'),
                                "on_crash": param.get_behavior('on_crash'),
                                "boot_dev": param.get_boot_dev(),
                                #"bootloader" : param.get_bootloader(),
                                #"commandline" : param.get_commandline(),
                                #"current_snapshot" : param.get_current_snapshot(),
                                'disk': param.get_disk(),
                                "domain_name": param.get_domain_name(),
                                "domain_type": param.get_domain_type(),
                                "features_acpi": param.get_features_acpi(),
                                "features_apic": param.get_features_apic(),
                                "features_pae": param.get_features_pae(),
                                #"initrd" : param.get_initrd(),
                                "interface": param.get_interface(),
                                #"kernel" : param.get_kernel(),
                                "max_memory": param.get_max_memory(),
                                'max_vcpus': param.get_max_vcpus(),
                                "max_vcpus_limit": param.get_max_vcpus_limit(),
                                "memory": param.get_memory(),
                                "uuid": param.get_uuid(),
                                "vcpus": param.get_vcpus(),
                                "vcpus_limit": param.get_vcpus_limit(),
                                "graphics_autoport":
                                param.get_graphics_autoport(),
                                "keymap": param.get_graphics_keymap(),
                                "graphics_listen": param.get_graphics_listen(),
                                "graphics_passwd": param.get_graphics_passwd(),
                                "graphics_port": param.get_graphics_port(),
                            },
                            "pool": pool[0].get_info(),
                        })
            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" %
                                 self.view.uuid)
                return web.badrequest()
            else:
                export = export[0]
        finally:
            kvc.close()

        # Pool running?
        if export['pool']['is_active'] is False:
            return web.badrequest(
                "The destination, the storage pool is not running.")

        dest_domname = export['xml']['domain_name']
        dest_uniqkey = export['info']['database']['uniq_key']
        # Same guest OS is already running.
        if m_findby1uniquekey(self.orm, dest_uniqkey) is not None:
            self.logger.info(
                _("guest '%s' already exists. (DB) - %s") %
                (dest_domname, dest_uniqkey))
            return web.badrequest(
                _("guest '%s' already exists.") % dest_domname)

        dest_dir = "%s/%s" % (export['pool']['target']['path'],
                              export['xml']['domain_name'])
        if os.path.exists(dest_dir) is True:
            self.logger.info(
                _("guest '%s' already exists. (FS) - %s") %
                (dest_domname, dest_dir))
            return web.badrequest(
                _("guest '%s' already exists.") % dest_domname)

        # disk check
        try:
            src_disk = "%s/%s/images/%s.img" \
                       % (export["info"]["dir"], export["info"]["name"], export["info"]["name"])

            if os.path.exists(src_disk):
                s_size = os.path.getsize(src_disk) / (1024 * 1024
                                                      )  # a unit 'MB'
                if chk_create_disk(export["info"]["dir"], s_size) is False:
                    partition = get_partition_info(export["info"]["dir"],
                                                   header=False)
                    return web.badrequest(
                        _("No space available to create disk image in '%s' partition.") \
                        % partition[5][0])
        except:
            pass

        extra_uniq_key = string_from_uuid(generate_uuid())
        options = {}
        options["exportuuid"] = export["info"]["uuid"]
        options["destuuid"] = extra_uniq_key
        options["quiet"] = None

        # Database Notebook
        try:
            _notebook = n_new(
                export["info"]["database"]["notebook"]["title"],
                export["info"]["database"]["notebook"]["value"],
            )
        except:
            _notebook = None

        # Database Tag
        _tags = []
        try:
            tag_array = comma_split(export["info"]["database"]["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))
        except:
            _tags.append(t_new(""))

        parent = m_findby1(self.orm, host_id)
        dest_guest = m_new(
            created_user=self.me,
            modified_user=self.me,
            uniq_key=extra_uniq_key,
            name=export["info"]["database"]["name"],
            attribute=int(export["info"]["database"]["attribute"]),
            hypervisor=int(export["info"]["database"]["hypervisor"]),
            notebook=_notebook,
            tags=_tags,
            icon=export["info"]["database"]["icon"],
            is_deleted=False,
            parent=parent,
        )

        ret = regist_guest(
            self,
            _guest=dest_guest,
            icon_filename=export["info"]["database"]["icon"],
            cmd=VIRT_COMMAND_IMPORT_GUEST,
            options=options,
            cmdname=['Import Guest', 'Import Guest'],
            rollback_options={"name": export["xml"]["domain_name"]},
            is_create=False)

        if ret is True:
            return web.accepted()
        else:
            return False
示例#10
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        kvc = KaresansuiVirtConnection()
        # #1 libvirt process
        try:
            #inactive_pool = kvc.list_inactive_storage_pool()
            inactive_pool = []
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            export = []
            for pool_name in pools:
                pool = 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,)):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != opts.uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            raise KssCommandException(
                                'Export corrupt data.(file not found) - path=%s' % path)

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            raise KssCommandException(
                                'Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                % (e_name, param.get_name()))

                        _dir = os.path.dirname(_afile)

                        export.append({"dir" : _dir,
                                       "pool" : pool_name,
                                       "uuid" : e_param.get_uuid(),
                                       "name" : e_name,
                                       })

            if len(export) < 1:
                # refresh pool.
                conn = KaresansuiVirtConnection(readonly=False)
                try:
                    conn.refresh_pools()
                finally:
                    conn.close()
                raise KssCommandException('libvirt data did not exist. - uuid=%s' % opts.uuid)
            else:
                export = export[0]

        finally:
            kvc.close()

        self.up_progress(30)
        # #2 physical process
        if os.path.isdir(export['dir']) is False:
            raise KssCommandException(_("Failed to delete export data. - %s") % (_("Export data directory not found. [%s]") % (export['dir'])))

        uuid = os.path.basename(export['dir'])
        pool_dir = os.path.dirname(export['dir'])

        if not is_uuid(export['uuid']):
            raise KssCommandException(_("Failed to delete export data. - %s") % (_("'%s' is not valid export data directory.") % (export['dir'])))

        shutil.rmtree(export['dir'])

        for _afile in glob.glob("%s*img" % (export['dir'])):
            os.remove(_afile)

        self.up_progress(30)
        # refresh pool.
        conn = KaresansuiVirtConnection(readonly=False)
        try:
            try:
                conn.refresh_pools()
            finally:
                conn.close()
        except:
            pass

        self.logger.info('Deleted export data. - uuid=%s' % (opts.uuid))
        print >>sys.stdout, _('Deleted export data. - uuid=%s') % (opts.uuid)
        return True