Exemplo n.º 1
0
    def _POST(self, *param, **params):
        if not validates_host_add(self):
            return web.badrequest(self.view.alert)

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

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

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

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

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

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

        name = self.input.m_name

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

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

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

            m_save(self.orm, host)
            return web.created(None)
        else:
            model.name = name
            model.hostname = hostname
            model.uniq_key = uniq_key
            model.notebook.title = note_title
            model.notebook.value = note_value
            model.tags = _tags
            model.is_deleted = False
            m_update(self.orm, model)
            return web.created(None)
Exemplo n.º 2
0
    def _POST(self, *param, **params):
        if not validates_host_add(self):
            return web.badrequest(self.view.alert)

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

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

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

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

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

        uniq_key = self.input.m_uuid
        name = self.input.m_name
        hostname = self.input.m_hostname

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

            m_save(self.orm, host)
            return web.created(None)
        else:
            model.name = name
            model.hostname = hostname
            model.uniq_key = uniq_key
            model.notebook.title = note_title
            model.notebook.value = note_value
            model.tags = _tags
            model.is_deleted = False
            m_update(self.orm, model)
            return web.created(None)
Exemplo n.º 3
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
Exemplo n.º 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
Exemplo n.º 5
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
Exemplo n.º 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 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
Exemplo n.º 7
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