Beispiel #1
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
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)

        self.up_progress(10)
        conn = KaresansuiVirtConnection(readonly=False)
        try:
            try:
                self.up_progress(10)
                progresscb = None
                if opts.debug is True:
                    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

                vol_obj = conn.get_storage_volume(opts.orig_pool, opts.orig_volume)
                if vol_obj is None:
                    raise KssCommandException(
                        'Specified storage volume does not exist. - pool=%s, vol=%s'
                        % (opts.orig_pool, opts.orig_volume))

                inactive_storage_pools = conn.list_inactive_storage_pool()
                active_storage_pools = conn.list_active_storage_pool()
                if not (opts.dest_pool in active_storage_pools or \
                            opts.dest_pool in inactive_storage_pools):
                    raise KssCommandException('Destination storage pool does not exist. - pool=%s'
                                              % (opts.dest_pool))

                vol_info = vol_obj.info()
                if vol_info[0] != 0:
                    raise KssCommandException(
                        'Specified storage volume does not "file" type. - pool=%s, vol=%s'
                        % (opts.orig_pool, opts.orig_volume))

                filesize = vol_info[1] / (1024 * 1024) # a unit 'MB'
                target_path = conn.get_storage_pool_targetpath(opts.dest_pool)
                if chk_create_disk(target_path, filesize) is False:
                    raise KssCommandException(
                        'Destination storage pool shortage capacity. - pool=%s'
                        % (opts.dest_pool))

                if conn.replicate_storage_volume(opts.orig_name,
                                                 opts.orig_pool,
                                                 opts.orig_volume,
                                                 opts.dest_name,
                                                 opts.dest_pool,
                                                 opts.dest_volume,
                                                 progresscb) is False:

                    raise KssCommandException(_("Failed to copy storage volume."))
                self.up_progress(40)
                self.logger.info('Replicate storage volume. - orig_pool=%s, orig_vol=%s, dest_pool=%s' % (opts.orig_pool, opts.orig_volume, opts.dest_pool))
                print >>sys.stdout, _('Replicate storage volume. - orig_pool=%s, orig_vol=%s, dest_pool=%s' % (opts.orig_pool, opts.orig_volume, opts.dest_pool))
                return True
            except Exception, e:
                raise e
        finally:
            conn.close()
Beispiel #3
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)

        self.up_progress(10)
        conn = KaresansuiVirtConnection(readonly=False)
        try:
            try:
                self.up_progress(10)
                progresscb = None
                if opts.debug is True:
                    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

                vol_obj = conn.get_storage_volume(opts.orig_pool,
                                                  opts.orig_volume)
                if vol_obj is None:
                    raise KssCommandException(
                        'Specified storage volume does not exist. - pool=%s, vol=%s'
                        % (opts.orig_pool, opts.orig_volume))

                inactive_storage_pools = conn.list_inactive_storage_pool()
                active_storage_pools = conn.list_active_storage_pool()
                if not (opts.dest_pool in active_storage_pools or \
                            opts.dest_pool in inactive_storage_pools):
                    raise KssCommandException(
                        'Destination storage pool does not exist. - pool=%s' %
                        (opts.dest_pool))

                vol_info = vol_obj.info()
                if vol_info[0] != 0:
                    raise KssCommandException(
                        'Specified storage volume does not "file" type. - pool=%s, vol=%s'
                        % (opts.orig_pool, opts.orig_volume))

                filesize = vol_info[1] / (1024 * 1024)  # a unit 'MB'
                target_path = conn.get_storage_pool_targetpath(opts.dest_pool)
                if chk_create_disk(target_path, filesize) is False:
                    raise KssCommandException(
                        'Destination storage pool shortage capacity. - pool=%s'
                        % (opts.dest_pool))

                if conn.replicate_storage_volume(
                        opts.orig_name, opts.orig_pool, opts.orig_volume,
                        opts.dest_name, opts.dest_pool, opts.dest_volume,
                        progresscb) is False:

                    raise KssCommandException(
                        _("Failed to copy storage volume."))
                self.up_progress(40)
                self.logger.info(
                    'Replicate storage volume. - orig_pool=%s, orig_vol=%s, dest_pool=%s'
                    % (opts.orig_pool, opts.orig_volume, opts.dest_pool))
                print >> sys.stdout, _(
                    'Replicate storage volume. - orig_pool=%s, orig_vol=%s, dest_pool=%s'
                    % (opts.orig_pool, opts.orig_volume, opts.dest_pool))
                return True
            except Exception, e:
                raise e
        finally:
            conn.close()
Beispiel #4
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

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

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

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

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

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

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

        uuid = string_from_uuid(generate_uuid())

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

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

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

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

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

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

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

        host = findbyhost1(self.orm, host_id)

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

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

        _notebook = n_new(note_title, note_value)

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

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

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

        ret =  regist_guest(self,
                            _guest,
                            icon_filename,
                            VIRT_COMMAND_CREATE_GUEST,
                            options,
                            ('Create Guest', 'Create Guest'),
                            {"name": options['name'],
                             "pool" : options["storage-pool"],
                             "volume" : options["uuid"],
                             },
                            is_create,
                            )
        if ret is True:
            return web.accepted()
        else:
            return False
Beispiel #5
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

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

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

        model = findbyguest1(self.orm, self.input.sid)
        if not model:
            return web.badrequest()

        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)

            src_pools = kvc.get_storage_pool_name_bydomain(domname)
            if not src_pools:
                return web.badrequest(_("Source storage pool is not found."))

            for src_pool in src_pools:
                src_pool_type = kvc.get_storage_pool_type(src_pool)
                if src_pool_type != 'dir':
                    return web.badrequest(
                        _("'%s' disk contains the image.") % src_pool_type)

            virt = kvc.search_kvg_guests(domname)[0]
            options = {}
            options["name"] = virt.get_domain_name()
            if is_param(self.input, "pool"):
                # disk check
                src_pool = kvc.get_storage_pool_name_bydomain(domname, 'os')[0]
                src_path = kvc.get_storage_pool_targetpath(src_pool)
                src_disk = "%s/%s/images/%s.img" \
                           % (src_path, options["name"], options["name"])

                dest_path = kvc.get_storage_pool_targetpath(self.input.pool)
                s_size = os.path.getsize(src_disk) / (1024 * 1024
                                                      )  # a unit 'MB'

                if os.access(dest_path, os.F_OK):
                    if chk_create_disk(dest_path, s_size) is False:
                        partition = get_partition_info(dest_path, header=False)
                        return web.badrequest(
                            _("No space available to create disk image in '%s' partition.") \
                                % partition[5][0])

                #else: # Permission denied
                #TODO:check disk space for root

                options["pool"] = self.input.pool

            if is_param(self.input, "export_title"):
                #options["title"] = self.input.export_title
                options["title"] = "b64:" + base64_encode(
                    self.input.export_title)
            options["quiet"] = None

        finally:
            kvc.close()

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

        # Job Register
        cmdname = ["Export Guest", "export guest"]
        _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,
        )

        self.logger.debug("(%s) Job group id==%s" % (cmdname[0], _jobgroup.id))
        url = '%s/job/%s.part' % (web.ctx.home, _jobgroup.id)
        self.logger.debug('Returning Location: %s' % url)

        return web.accepted()
Beispiel #6
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 model.attribute == 0 and model.hypervisor == MACHINE_HYPERVISOR[
                "XEN"]:
            uri = uris["XEN"]
        elif model.attribute == 0 and model.hypervisor == MACHINE_HYPERVISOR[
                "KVM"]:
            uri = uris["KVM"]
        else:
            uri = None

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

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

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

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

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

        uuid = string_from_uuid(generate_uuid())

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

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

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

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

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

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

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

        host = findbyhost1(self.orm, host_id)

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

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

        _notebook = n_new(note_title, note_value)

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

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

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

        ret = regist_guest(
            self,
            _guest,
            icon_filename,
            VIRT_COMMAND_CREATE_GUEST,
            options,
            ('Create Guest', 'Create Guest'),
            {
                "name": options['name'],
                "pool": options["storage-pool"],
                "volume": options["uuid"],
            },
            is_create,
        )
        if ret is True:
            return web.accepted()
        else:
            return False
Beispiel #7
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

        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
Beispiel #8
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

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

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

        model = findbyguest1(self.orm, self.input.sid)
        if not model:
            return web.badrequest()

        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)

            src_pools = kvc.get_storage_pool_name_bydomain(domname)
            if not src_pools:
                return web.badrequest(_("Source storage pool is not found."))

            for src_pool in  src_pools :
                src_pool_type = kvc.get_storage_pool_type(src_pool)
                if src_pool_type != 'dir':
                    return web.badrequest(_("'%s' disk contains the image.") % src_pool_type)

            virt = kvc.search_kvg_guests(domname)[0]
            options = {}
            options["name"] = virt.get_domain_name()
            if is_param(self.input, "pool"):
                # disk check
                src_pool = kvc.get_storage_pool_name_bydomain(domname, 'os')[0]
                src_path = kvc.get_storage_pool_targetpath(src_pool)
                src_disk = "%s/%s/images/%s.img" \
                           % (src_path, options["name"], options["name"])

                dest_path = kvc.get_storage_pool_targetpath(self.input.pool)
                s_size = os.path.getsize(src_disk) / (1024 * 1024) # a unit 'MB'

                if os.access(dest_path, os.F_OK):
                    if chk_create_disk(dest_path, s_size) is False:
                        partition = get_partition_info(dest_path, header=False)
                        return web.badrequest(
                            _("No space available to create disk image in '%s' partition.") \
                                % partition[5][0])

                #else: # Permission denied
                    #TODO:check disk space for root

                options["pool"] = self.input.pool

            if is_param(self.input, "export_title"):
                #options["title"] = self.input.export_title
                options["title"] = "b64:" + base64_encode(self.input.export_title)
            options["quiet"] = None

        finally:
            kvc.close()

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

        # Job Register
        cmdname = ["Export Guest", "export guest"]
        _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,
                               )

        self.logger.debug("(%s) Job group id==%s" % (cmdname[0],_jobgroup.id))
        url = '%s/job/%s.part' % (web.ctx.home, _jobgroup.id)
        self.logger.debug('Returning Location: %s' % url)

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

        if not validates_guest_replicate(self):
            self.logger.debug(self.view.alert)
            return web.badrequest(self.view.alert)

        uuid = string_from_uuid(generate_uuid())

        # TODO dest_pool valid
        if not validates_src_id(self):
            self.logger.debug(self.view.alert)
            return web.badrequest(self.view.alert)

        src_guest = findbyguest1(self.orm, self.input.src_id)
        if not src_guest:
            self.view.alert = "Failed to get the data of source domain."
            self.logger.debug(self.view.alert)
            return web.badrequest(self.view.alert)

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

        # Tag
        _tags = None
        if is_param(self.input, "tags"):
            _tags = []
            for x in comma_split(self.input.tags):
                _tags.append(t_new(x))

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

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


        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(src_guest.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            options = {}
            options["src-name"] = virt.get_domain_name()
            if is_param(self.input, "dest_pool"):
                options["pool"] = self.input.dest_pool
            if is_param(self.input, "domain_dest_name"):
                options["dest-name"] = self.input.domain_dest_name
            if is_param(self.input, "vm_vncport"):
                options["vnc-port"] = self.input.vm_vncport
            if is_param(self.input, "vm_mac"):
                options["mac"] = self.input.vm_mac

            options["uuid"] = uuid

            src_pools = kvc.get_storage_pool_name_bydomain(domname)
            if not src_pools:
                self.view.alert = _("Source storage pool is not found.")
                self.logger.debug(self.view.alert)
                return web.badrequest(self.view.alert)

            for src_pool in  src_pools :
                src_pool_type = kvc.get_storage_pool_type(src_pool)
                if src_pool_type != 'dir':
                    self.view.alert = _("'%s' disk contains the image.") % src_pool_type
                    self.logger.debug(self.view.alert)
                    return web.badrequest(self.view.alert)

            # disk check
            target_pool = kvc.get_storage_pool_name_bydomain(domname, 'os')[0]
            target_path = kvc.get_storage_pool_targetpath(target_pool)
            src_disk = "%s/%s/images/%s.img" % \
                                      (target_path, options["src-name"], options["src-name"])

            s_size = os.path.getsize(src_disk) / (1024 * 1024) # a unit 'MB'

            if os.access(target_path, os.F_OK):
                if chk_create_disk(target_path, s_size) is False:
                    partition = get_partition_info(target_path, header=False)
                    self.view.alert = _("No space available to create disk image in '%s' partition.") % partition[5][0]
                    self.logger.debug(self.view.alert)
                    return web.badrequest(self.view.alert)

            #else: # Permission denied
                #TODO:check disk space for root

            active_guests = kvc.list_active_guest()
            inactive_guests = kvc.list_inactive_guest()
            used_vnc_ports = kvc.list_used_vnc_port()
            used_mac_addrs = kvc.list_used_mac_addr()

            conflict_location = "%s/host/%d/guest/%d.json" \
                                % (web.ctx.homepath, src_guest.parent_id, src_guest.id)
            # source guestos
            if not (options["src-name"] in active_guests or options["src-name"] in inactive_guests):
                return web.conflict(conflict_location, "Unable to get the source guest.")

            # Check on whether value has already been used
            # destination guestos
            if (options["dest-name"] in active_guests or options["dest-name"] in inactive_guests):
                return web.conflict(conflict_location, "Destination guest %s is already there." % options["dest-name"])
            # VNC port number
            if(int(self.input.vm_vncport) in used_vnc_ports):
                return web.conflict(conflict_location, "VNC port %s is already used." % self.input.vm_vncport)
            # MAC address
            if(self.input.vm_mac in used_mac_addrs):
                return web.conflict(conflict_location, "MAC address %s is already used." % self.input.vm_mac)

            # Replicate Guest
            order = 0 # job order
            disk_jobs = [] # Add Disk
            volume_jobs = [] # Create Storage Volume
            for disk in virt.get_disk_info():
                if disk['type'] != 'file':
                    self.view.alert = _("The type of the storage pool where the disk is to be added must be 'file'. dev=%s") % disk['target']['dev']
                    self.logger.debug(self.view.alert)
                    return web.badrequest(self.view.alert)

                disk_pool = kvc.get_storage_pool_name_byimage(disk['source']['file'])
                if not disk_pool:
                    self.view.alert = _("Can not find the storage pool.")
                    self.logger.debug(self.view.alert)
                    return web.badrequest(self.view.alert)
                else:
                    disk_pool = disk_pool[0]

                disk_volumes = kvc.get_storage_volume_bydomain(domname, 'disk', 'key')
                volume = None
                for key in disk_volumes.keys():
                    if disk['source']['file'] == os.path.realpath(disk_volumes[key]):
                        volume = key # disk image

                if volume is None: # os image
                    continue

                disk_uuid = string_from_uuid(generate_uuid())

                volume_jobs.append(replicate_storage_volume(self,
                                                     domname,
                                                     disk_pool,
                                                     volume,
                                                     self.input.domain_dest_name,
                                                     #self.input.dest_pool,
                                                     disk_pool, # orig
                                                     disk_uuid,
                                                     order))
                order += 1

                disk_jobs.append(create_disk_job(self,
                                                 dest_guest,
                                                 self.input.domain_dest_name,
                                                 disk_pool,
                                                 disk_uuid,
                                                 bus=disk['target']['bus'],
                                                 format=disk['driver']['type'],
                                                 type=disk['type'],
                                                 target=disk['target']['dev'],
                                                 order=-1))

        finally:
            kvc.close()


        # replicate guest
        guest_job = replicate_guest(self,
                                    dest_guest,
                                    VIRT_COMMAND_REPLICATE_GUEST,
                                    options,
                                    'Replicate Guest',
                                    {"name" : options['dest-name'],
                                     "pool" : options["pool"],
                                     },
                                    order,
                                    )
        order += 1
        for disk_job in disk_jobs:
            disk_job.order = order
            order += 1

        ret = exec_replicate_guest(self,
                                   dest_guest,
                                   icon_filename,
                                   'Replicate Guest',
                                   guest_job,
                                   disk_jobs,
                                   volume_jobs,
                                   )

        if ret is True:
            return web.accepted()
        else:
            return False