Example #1
0
def plugin_selector_to_dict(selector):
    from karesansui.lib.utils import comma_split
    selector_arr = comma_split(selector)
    selector_dict = dict()

    for select in selector_arr:
        (key, val) = select.split(':', 2)
        selector_dict[key] = val

    return selector_dict
Example #2
0
def plugin_selector_to_dict(selector):
    from karesansui.lib.utils import comma_split
    selector_arr = comma_split(selector)
    selector_dict = dict()

    for select in selector_arr:
        (key, val) = select.split(':',2)
        selector_dict[key] = val

    return selector_dict
Example #3
0
def threshold_value_to_dict(value):
    from karesansui.lib.utils import comma_split
    value_arr = comma_split(value)
    value_dict = dict()

    for value in value_arr:
        (key, val) = value.split(':',2)
        value_dict[key] = val

    return value_dict
Example #4
0
def threshold_value_to_dict(value):
    from karesansui.lib.utils import comma_split
    value_arr = comma_split(value)
    value_dict = dict()

    for value in value_arr:
        (key, val) = value.split(':', 2)
        value_dict[key] = val

    return value_dict
Example #5
0
def validates_guest_edit(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if not is_param(obj.input, 'm_name'):
        check = False
        checker.add_error(_('Parameter m_name does not exist.'))
    else:
        check = checker.check_string(
                    _('Machine Name'),
                    obj.input.m_name,
                    CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = MACHINE_NAME_MIN_LENGTH,
                    max = MACHINE_NAME_MAX_LENGTH,
            ) and check

    if is_param(obj.input, 'note_title'):
        check = checker.check_string(
                    _('Title'),
                    obj.input.note_title,
                    CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = NOTE_TITLE_MIN_LENGTH,
                    max = NOTE_TITLE_MAX_LENGTH,
                ) and check

    if is_param(obj.input, 'note_value'):
        check = checker.check_string(
                    _('Note'),
                    obj.input.note_value,
                    CHECK_ONLYSPACE,
                    None,
                    None,
                    None,
                ) and check


    if is_param(obj.input, 'tags'):
        for tag in comma_split(obj.input.tags):
            check = checker.check_string(
                        _('Tag'),
                        tag,
                        CHECK_LENGTH | CHECK_ONLYSPACE,
                        None,
                        min = TAG_MIN_LENGTH,
                        max = TAG_MAX_LENGTH,
                    ) and check

    obj.view.alert = checker.errors
    return check
Example #6
0
def validates_guest_edit(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if not is_param(obj.input, 'm_name'):
        check = False
        checker.add_error(_('Parameter m_name does not exist.'))
    else:
        check = checker.check_string(
            _('Machine Name'),
            obj.input.m_name,
            CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE,
            None,
            min=MACHINE_NAME_MIN_LENGTH,
            max=MACHINE_NAME_MAX_LENGTH,
        ) and check

    if is_param(obj.input, 'note_title'):
        check = checker.check_string(
            _('Title'),
            obj.input.note_title,
            CHECK_LENGTH | CHECK_ONLYSPACE,
            None,
            min=NOTE_TITLE_MIN_LENGTH,
            max=NOTE_TITLE_MAX_LENGTH,
        ) and check

    if is_param(obj.input, 'note_value'):
        check = checker.check_string(
            _('Note'),
            obj.input.note_value,
            CHECK_ONLYSPACE,
            None,
            None,
            None,
        ) and check

    if is_param(obj.input, 'tags'):
        for tag in comma_split(obj.input.tags):
            check = checker.check_string(
                _('Tag'),
                tag,
                CHECK_LENGTH | CHECK_ONLYSPACE,
                None,
                min=TAG_MIN_LENGTH,
                max=TAG_MAX_LENGTH,
            ) and check

    obj.view.alert = checker.errors
    return check
Example #7
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()
        
        if not validates_host_edit(self):
            self.logger.debug("Update Host OS is failed, Invalid input value.")
            return web.badrequest(self.view.alert)

        host = findbyhost1(self.orm, host_id)

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

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

        if is_param(self.input, "m_hostname"):
            host.hostname = self.input.m_hostname
        if is_param(self.input, "note_title"):
            host.notebook.title = self.input.note_title
        if is_param(self.input, "note_value"):
            host.notebook.value = self.input.note_value
        if is_param(self.input, "m_name"):
            host.name = self.input.m_name
    
        # Icon
        icon_filename = None
        if is_param(self.input, "icon_filename", empty=True):
            host.icon = self.input.icon_filename

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

        host.modified_user = self.me

        m_update(self.orm, host)

        return web.seeother(web.ctx.path)
Example #8
0
    def _PUT(self, *param, **params):

        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None:
            return web.notfound()

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

        guest = findbyguest1(self.orm, guest_id)

        # notebook
        if is_param(self.input, "note_title"):
            guest.notebook.title = self.input.note_title
        if is_param(self.input, "note_value"):
            guest.notebook.value = self.input.note_value

        if is_param(self.input, "m_name"):
            guest.name = self.input.m_name

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

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

        guest.modified_user = self.me

        m_update(self.orm, guest)
        return web.seeother(web.ctx.path)
Example #9
0
    def _PUT(self, *param, **params):

        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None:
            return web.notfound()

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

        guest = findbyguest1(self.orm, guest_id)

        # notebook
        if is_param(self.input, "note_title"):
            guest.notebook.title = self.input.note_title
        if is_param(self.input, "note_value"):
            guest.notebook.value = self.input.note_value

        if is_param(self.input, "m_name"):
            guest.name = self.input.m_name

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

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

        guest.modified_user = self.me

        m_update(self.orm, guest)
        return web.seeother(web.ctx.path)
Example #10
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
Example #11
0
def validates_host_add(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if not is_param(obj.input, 'm_name'):
        check = False
        checker.add_error(_('Parameter m_name does not exist.'))
    else:
        check = checker.check_string(
                    _('Machine Name'),
                    obj.input.m_name,
                    CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = MACHINE_NAME_MIN_LENGTH,
                    max = MACHINE_NAME_MAX_LENGTH,
            ) and check

    if not is_param(obj.input, 'm_hostname'):
        check = False
        checker.add_error(_('"%s" is required.') % _('FQDN'))
    else:
        m_hostname_parts = obj.input.m_hostname.split(":")
        if len(m_hostname_parts) > 2:
            check = False
            checker.add_error(_('%s contains too many colon(:)s.') % _('FQDN'))
        else:
            check = checker.check_domainname(
                        _('FQDN'),
                        m_hostname_parts[0],
                        CHECK_EMPTY | CHECK_LENGTH | CHECK_VALID,
                        min = FQDN_MIN_LENGTH,
                        max = FQDN_MAX_LENGTH,
                        ) and check
            try:
                check = checker.check_number(
                            _('Port Number'),
                            m_hostname_parts[1],
                            CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX,
                            PORT_MIN_NUMBER,
                            PORT_MAX_NUMBER,
                            ) and check
            except IndexError:
                # when reach here, 'm_hostname' has only host name
                pass

    if not is_param(obj.input, 'm_uuid'):
        check = False
        checker.add_error(_('"%s" is required.') % _('Unique Key'))
    else:
        check = checker.check_unique_key(
                    _('Unique Key'),
                    obj.input.m_uuid,
                    CHECK_EMPTY | CHECK_VALID
                    ) and check

    if is_param(obj.input, 'note_title'):
        check = checker.check_string(
                    _('Title'),
                    obj.input.note_title,
                    CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = NOTE_TITLE_MIN_LENGTH,
                    max = NOTE_TITLE_MAX_LENGTH,
                ) and check

    if is_param(obj.input, 'note_value'):
        check = checker.check_string(
                    _('Note'),
                    obj.input.note_value,
                    CHECK_ONLYSPACE,
                    None,
                    None,
                    None,
                ) and check

    if is_param(obj.input, 'tags'):
        for tag in comma_split(obj.input.tags):
            check = checker.check_string(
                        _('Tag'),
                        tag,
                        CHECK_LENGTH | CHECK_ONLYSPACE,
                        None,
                        min = TAG_MIN_LENGTH,
                        max = TAG_MAX_LENGTH,
                    ) and check

    obj.view.alert = checker.errors
    return check
Example #12
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)
Example #13
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
Example #14
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
Example #15
0
    def _POST(self, *param, **params):
        if not validates_host_add(self):
            return web.badrequest(self.view.alert)

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

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

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

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

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

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

        name = self.input.m_name

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

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

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

            m_save(self.orm, host)
            return web.created(None)
        else:
            model.name = name
            model.hostname = hostname
            model.uniq_key = uniq_key
            model.notebook.title = note_title
            model.notebook.value = note_value
            model.tags = _tags
            model.is_deleted = False
            m_update(self.orm, model)
            return web.created(None)
Example #16
0
def validates_guest_replicate(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if not is_param(obj.input, 'm_name'):
        check = False
        checker.add_error(_('Parameter m_name does not exist.'))
    else:
        check = checker.check_string(
                    _('Machine Name'),
                    obj.input.m_name,
                    CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = MACHINE_NAME_MIN_LENGTH,
                    max = MACHINE_NAME_MAX_LENGTH,
            ) and check

    if is_param(obj.input, 'note_title'):
        check = checker.check_string(
                    _('Title'),
                    obj.input.note_title,
                    CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = NOTE_TITLE_MIN_LENGTH,
                    max = NOTE_TITLE_MAX_LENGTH,
                ) and check

    if is_param(obj.input, 'note_value'):
        check = checker.check_string(
                    _('Note'),
                    obj.input.note_value,
                    CHECK_ONLYSPACE,
                    None,
                    None,
                    None,
                ) and check

    if is_param(obj.input, 'tags'):
        for tag in comma_split(obj.input.tags):
            check = checker.check_string(
                        _('Tag'),
                        tag,
                        CHECK_LENGTH | CHECK_ONLYSPACE,
                        None,
                        min = TAG_MIN_LENGTH,
                        max = TAG_MAX_LENGTH,
                    ) and check

    if not is_param(obj.input, 'domain_dest_name'):
        check = False
        checker.add_error(_('Parameter domain_dest_name does not exist.'))
    else:
        check = checker.check_string(
                _('Destination Domain Name'),
                obj.input.domain_dest_name,
                CHECK_EMPTY | CHECK_VALID | CHECK_LENGTH,
                '[^-a-zA-Z0-9_\.]+',
                DOMAIN_NAME_MIN_LENGTH,
                DOMAIN_NAME_MAX_LENGTH,
            ) and check

    if not is_param(obj.input, 'vm_vncport'):
        check = False
        checker.add_error(_('Parameter vm_vncport does not exist.'))
    else:
        check = checker.check_number(
                _('VNC Port Number'),
                obj.input.vm_vncport,
                CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX,
                VNC_PORT_MIN_NUMBER,
                VNC_PORT_MAX_NUMBER,
            ) and check

    if not is_param(obj.input, 'vm_mac'):
        check = False
        checker.add_error(_('Parameter vm_mac does not exist.'))
    else:
        check = checker.check_macaddr(
                _('MAC Address'),
                obj.input.vm_mac,
                CHECK_EMPTY | CHECK_VALID,
            ) and check

    obj.view.alert = checker.errors
    return check
Example #17
0
def validates_guest_add(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if not is_param(obj.input, 'm_name'):
        check = False
        checker.add_error(_('Parameter m_name does not exist.'))
    else:
        check = checker.check_string(
            _('Machine Name'),
            obj.input.m_name,
            CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE,
            None,
            min=MACHINE_NAME_MIN_LENGTH,
            max=MACHINE_NAME_MAX_LENGTH,
        ) and check

    if is_param(obj.input, 'note_title'):
        check = checker.check_string(
            _('Title'),
            obj.input.note_title,
            CHECK_LENGTH | CHECK_ONLYSPACE,
            None,
            min=NOTE_TITLE_MIN_LENGTH,
            max=NOTE_TITLE_MAX_LENGTH,
        ) and check

    if is_param(obj.input, 'note_value'):
        check = checker.check_string(
            _('Note'),
            obj.input.note_value,
            CHECK_ONLYSPACE,
            None,
            None,
            None,
        ) and check

    if is_param(obj.input, 'tags'):
        for tag in comma_split(obj.input.tags):
            check = checker.check_string(
                _('Tag'),
                tag,
                CHECK_LENGTH | CHECK_ONLYSPACE,
                None,
                min=TAG_MIN_LENGTH,
                max=TAG_MAX_LENGTH,
            ) and check

    if not is_param(obj.input, 'm_hypervisor'):
        check = False
        checker.add_error(_('Parameter m_hypervisor does not exist.'))
    else:
        check = checker.check_hypervisor(
            _('Hypervisor'),
            obj.input.m_hypervisor,
            CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX,
            HYPERVISOR_MIN_SIZE,
            HYPERVISOR_MAX_SIZE,
        ) and check

    if not is_param(obj.input, 'domain_name'):
        check = False
        checker.add_error(_('Parameter domain_name does not exist.'))
    else:
        check = checker.check_string(
            _('Domain Name'),
            obj.input.domain_name,
            CHECK_EMPTY | CHECK_VALID | CHECK_LENGTH | CHECK_ONLYSPACE,
            '[^-a-zA-Z0-9_\.]+',
            DOMAIN_NAME_MIN_LENGTH,
            DOMAIN_NAME_MAX_LENGTH,
        ) and check

        if obj.input.domain_name in get_dom_list():
            dom_type = get_dom_type(obj.input.domain_name)
            checker.add_error(
                _("The same domain name already exists for hypervisor '%s'.") %
                dom_type.upper())
            check = False

    if is_param(obj.input, 'vm_mem_size'):
        check = checker.check_number(
            _('Memory Size (MB)'),
            obj.input.vm_mem_size,
            CHECK_VALID | CHECK_MIN | CHECK_EMPTY,
            MEMORY_MIN_SIZE,
            None,
        ) and check

    if is_param(obj.input, 'pool_type'):
        if obj.input.pool_type != "block":
            if is_param(obj.input, 'vm_disk_size'):
                check = checker.check_number(
                    _('Disk Size (MB)'),
                    obj.input.vm_disk_size,
                    CHECK_VALID | CHECK_MIN | CHECK_EMPTY,
                    DISK_MIN_SIZE,
                    None,
                ) and check

    if not is_param(obj.input, 'boot_image'):
        check = False
        checker.add_error(_('Parameter boot_image does not exist.'))
    else:
        if obj.input.boot_image == "kernel":
            if not is_param(obj.input, 'vm_kernel'):
                check = False
                checker.add_error(_('Parameter vm_kernel does not exist.'))
            else:
                check = checker.check_startfile(
                    _('Kernel Image'),
                    obj.input.vm_kernel,
                    CHECK_EMPTY | CHECK_VALID | CHECK_EXIST,
                ) and check

            if not is_param(obj.input, 'vm_initrd'):
                check = False
                checker.add_error(_('Parameter vm_initrd does not exist.'))
            else:
                check = checker.check_startfile(
                    _('Initrd Image'),
                    obj.input.vm_initrd,
                    CHECK_EMPTY | CHECK_VALID | CHECK_EXIST,
                ) and check

        if obj.input.boot_image == "iso":
            if not is_param(obj.input, 'vm_iso'):
                check = False
                checker.add_error(_('Parameter vm_iso does not exist.'))
            else:
                check = checker.check_startfile(
                    _('ISO Image'),
                    obj.input.vm_iso,
                    CHECK_EMPTY | CHECK_VALID | CHECK_EXIST,
                ) and check
                if check:
                    check = is_iso9660_filesystem_format(obj.input.vm_iso)
                    checker.add_error(
                        _('"%s" is not valid ISO 9660 CD-ROM filesystem data.')
                        % obj.input.vm_iso)

    if not is_param(obj.input, 'keymap'):
        check = False
        checker.add_error(_('"%s" is required.') % _('Graphics Keymap'))
    else:
        hypervisor = "KVM"
        if int(obj.input.m_hypervisor) == MACHINE_HYPERVISOR['XEN']:
            hypervisor = "XEN"
        elif int(obj.input.m_hypervisor) == MACHINE_HYPERVISOR['KVM']:
            hypervisor = "KVM"
        check = checker.check_keymap(_('Graphics Keymap'), obj.input.keymap,
                                     CHECK_EMPTY | CHECK_EXIST,
                                     hypervisor) and check

    if not is_param(obj.input, 'vm_graphics_port'):
        check = False
        checker.add_error(_('Parameter vm_graphics_port does not exist.'))
    else:
        check = checker.check_number(
            _('Graphics Port Number'),
            obj.input.vm_graphics_port,
            CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX,
            GRAPHICS_PORT_MIN_NUMBER,
            GRAPHICS_PORT_MAX_NUMBER,
        ) and check

    if not is_param(obj.input, 'vm_mac'):
        check = False
        checker.add_error(_('Parameter vm_mac does not exist.'))
    else:
        check = checker.check_macaddr(
            _('MAC Address'),
            obj.input.vm_mac,
            CHECK_EMPTY | CHECK_VALID,
        ) and check

    obj.view.alert = checker.errors
    return check
Example #18
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

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

        host = findbyhost1(self.orm, host_id)

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

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

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

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

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

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

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

        host.modified_user = self.me

        m_update(self.orm, host)

        return web.seeother(web.ctx.path)
Example #19
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        dev_list = comma_split(opts.dev)
        if len(dev_list) < 2:
            # TRANSLATORS:
            #    bondingするためのdeviceが少ないです
            raise KssCommandOptException('ERROR: Small device for bonding. - dev=%s' % (opts.dev))

        interface_list = get_ifconfig_info()
        for dev in dev_list:
            if dev not in interface_list:
                raise KssCommandOptException('ERROR: Bonding target device not found. - dev=%s' % (dev))

        if opts.primary not in dev_list:
            raise KssCommandOptException('ERROR: Primary device not found in bonding device. - primary=%s dev=%s' % (opts.primary, opts.dev))

        exist_bond_max_num = -1
        exist_bond_list = get_ifconfig_info("regex:^bond")
        for bond_name in exist_bond_list.keys():
            try:
                num = int(bond_name.replace("bond",""))
            except ValueError:
                continue

            if exist_bond_max_num < num:
                exist_bond_max_num = num

        self.up_progress(10)
        physical_bond_name = "bond%s" % (exist_bond_max_num + 1)
        bridge_bond_name = "bondbr%s" % (exist_bond_max_num + 1)
        bond_options = '"mode=%s primary=%s miimon=%s"' % (opts.mode, opts.primary, BONDING_CONFIG_MII_DEFAULT)
        self.up_progress(10)

        dop = DictOp()
        ifcfg_parser = ifcfgParser()
        modprobe_parser = modprobe_confParser()

        dop.addconf("ifcfg", ifcfg_parser.read_conf())
        if dop.getconf("ifcfg") == {}:
            raise KssCommandException('Failure read network config file.')

        dop.addconf("modprobe_conf", modprobe_parser.read_conf())
        if dop.getconf("modprobe_conf") == {}:
            raise KssCommandException('Failure read modprobe config file.')

        self.up_progress(10)
        eth_conf_copykey = ["HWADDR",
                            "BOOTPROTO",
                            "ONBOOT",
                            "USERCTL",
                            ]
        bond_conf_nocopykey = ["TYPE",
                               "HWADDR",
                               "MACADDR",
                               "ETHTOOL_OPTS",
                               "ESSID",
                               "CHANNEL",
                               ]

        self.up_progress(10)
        for dev in dev_list:
            conf = dop.get("ifcfg", dev)
            if dev == opts.primary:
                primary_conf = copy.deepcopy(conf)

            dop.unset("ifcfg", dev)
            dop.set("ifcfg", [dev, "DEVICE"], conf["DEVICE"]["value"])
            for key in eth_conf_copykey:
                if key in conf:
                    dop.set("ifcfg", [dev, key], conf[key]["value"])
            dop.set("ifcfg", [dev, "MASTER"], physical_bond_name)
            dop.set("ifcfg", [dev, "SLAVE"], "yes")
            dop.set("ifcfg", [dev, "BOOTPROTO"], "none")

            if dop.get("ifcfg", "p%s" % (dev)):
                hwaddr = dop.get("ifcfg", ["p%s" % (dev), "HWADDR"])
                if hwaddr:
                    dop.set("ifcfg", [dev, "HWADDR"], hwaddr)
                dop.unset("ifcfg", "p%s" % (dev))

        for key in bond_conf_nocopykey:
            if key in primary_conf:
                del primary_conf[key]

        dop.set("ifcfg", bridge_bond_name, primary_conf)
        dop.set("ifcfg", [bridge_bond_name, "DEVICE"], bridge_bond_name)
        dop.set("ifcfg", [bridge_bond_name, "TYPE"], "Bridge")

        dop.set("ifcfg", [physical_bond_name, "DEVICE"], physical_bond_name)
        dop.set("ifcfg", [physical_bond_name, "BRIDGE"], bridge_bond_name)
        dop.set("ifcfg", [physical_bond_name, "BOOTPROTO"], "none")
        dop.set("ifcfg", [physical_bond_name, "ONBOOT"], dop.get("ifcfg", [bridge_bond_name, "ONBOOT"]))
        dop.set("ifcfg", [physical_bond_name, "BONDING_OPTS"], bond_options)

        self.up_progress(10)
        dop.set("modprobe_conf", ["alias", physical_bond_name], "bonding")

        for dev in dev_list:
            if os.path.isfile("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev)):
                copy_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev), VENDOR_DATA_BONDING_EVACUATION_DIR)
            if os.path.isfile("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev)):
                move_file("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev), VENDOR_DATA_BONDING_EVACUATION_DIR)

        if ifcfg_parser.write_conf(dop.getconf("ifcfg")) is False:
            raise KssCommandException('Failure write network config file.')

        if modprobe_parser.write_conf(dop.getconf("modprobe_conf")) is False:
            raise KssCommandException('Failure write modprobe config file.')

        self.up_progress(10)
        #
        # Delete bridge device
        #
        bridge_list = get_bridge_info()
        for dev in dev_list:
            if dev in bridge_list:
                ifdown_cmd = (NETWORK_IFDOWN_COMMAND,
                              dev,
                              )
                (ifdown_rc, ifdown_res) = execute_command(ifdown_cmd)
                if ifdown_rc != 0:
                    raise KssCommandException('Failure stop interface. interface:%s' % (dev))

                for brif in bridge_list[dev]:
                    brctl_delif_cmd = (NETWORK_BRCTL_COMMAND,
                                       "delif",
                                       dev,
                                       brif,
                                       )
                    (brctl_rc, brctl_res) = execute_command(brctl_delif_cmd)
                    if brctl_rc != 0:
                        raise KssCommandException('Failure delete bridge port. bridge:%s port:%s' % (dev, brif))

                brctl_delbr_cmd = (NETWORK_BRCTL_COMMAND,
                                   "delbr",
                                   dev,
                                   )
                (brctl_rc, brctl_res) = execute_command(brctl_delbr_cmd)
                if brctl_rc != 0:
                    raise KssCommandException('Failure delete bridge. bridge:%s' % (dev, brif))

        self.up_progress(10)
        #
        # Restart network
        #
        network_restart_cmd = (NETWORK_COMMAND,
                               "restart",
                               )
        (net_rc, net_res) = execute_command(network_restart_cmd)
        if net_rc != 0:
            raise KssCommandException('Failure restart network.')

        self.logger.info("Created bonding device. - dev=%s bond=%s" % (opts.dev, bridge_bond_name))
        print >>sys.stdout, _("Created bonding device. - dev=%s bond=%s" % (opts.dev, bridge_bond_name))

        return True
Example #20
0
    def process(self):
        (opts, args) = getopts()
        chkopts(opts)
        self.up_progress(10)

        dev_list = comma_split(opts.dev)
        if len(dev_list) < 2:
            # TRANSLATORS:
            #    bondingするためのdeviceが少ないです
            raise KssCommandOptException(
                'ERROR: Small device for bonding. - dev=%s' % (opts.dev))

        interface_list = get_ifconfig_info()
        for dev in dev_list:
            if dev not in interface_list:
                raise KssCommandOptException(
                    'ERROR: Bonding target device not found. - dev=%s' % (dev))

        if opts.primary not in dev_list:
            raise KssCommandOptException(
                'ERROR: Primary device not found in bonding device. - primary=%s dev=%s'
                % (opts.primary, opts.dev))

        exist_bond_max_num = -1
        exist_bond_list = get_ifconfig_info("regex:^bond")
        for bond_name in exist_bond_list.keys():
            try:
                num = int(bond_name.replace("bond", ""))
            except ValueError:
                continue

            if exist_bond_max_num < num:
                exist_bond_max_num = num

        self.up_progress(10)
        physical_bond_name = "bond%s" % (exist_bond_max_num + 1)
        bridge_bond_name = "bondbr%s" % (exist_bond_max_num + 1)
        bond_options = '"mode=%s primary=%s miimon=%s"' % (
            opts.mode, opts.primary, BONDING_CONFIG_MII_DEFAULT)
        self.up_progress(10)

        dop = DictOp()
        ifcfg_parser = ifcfgParser()
        modprobe_parser = modprobe_confParser()

        dop.addconf("ifcfg", ifcfg_parser.read_conf())
        if dop.getconf("ifcfg") == {}:
            raise KssCommandException('Failure read network config file.')

        dop.addconf("modprobe_conf", modprobe_parser.read_conf())
        if dop.getconf("modprobe_conf") == {}:
            raise KssCommandException('Failure read modprobe config file.')

        self.up_progress(10)
        eth_conf_copykey = [
            "HWADDR",
            "BOOTPROTO",
            "ONBOOT",
            "USERCTL",
        ]
        bond_conf_nocopykey = [
            "TYPE",
            "HWADDR",
            "MACADDR",
            "ETHTOOL_OPTS",
            "ESSID",
            "CHANNEL",
        ]

        self.up_progress(10)
        for dev in dev_list:
            conf = dop.get("ifcfg", dev)
            if dev == opts.primary:
                primary_conf = copy.deepcopy(conf)

            dop.unset("ifcfg", dev)
            dop.set("ifcfg", [dev, "DEVICE"], conf["DEVICE"]["value"])
            for key in eth_conf_copykey:
                if key in conf:
                    dop.set("ifcfg", [dev, key], conf[key]["value"])
            dop.set("ifcfg", [dev, "MASTER"], physical_bond_name)
            dop.set("ifcfg", [dev, "SLAVE"], "yes")
            dop.set("ifcfg", [dev, "BOOTPROTO"], "none")

            if dop.get("ifcfg", "p%s" % (dev)):
                hwaddr = dop.get("ifcfg", ["p%s" % (dev), "HWADDR"])
                if hwaddr:
                    dop.set("ifcfg", [dev, "HWADDR"], hwaddr)
                dop.unset("ifcfg", "p%s" % (dev))

        for key in bond_conf_nocopykey:
            if key in primary_conf:
                del primary_conf[key]

        dop.set("ifcfg", bridge_bond_name, primary_conf)
        dop.set("ifcfg", [bridge_bond_name, "DEVICE"], bridge_bond_name)
        dop.set("ifcfg", [bridge_bond_name, "TYPE"], "Bridge")

        dop.set("ifcfg", [physical_bond_name, "DEVICE"], physical_bond_name)
        dop.set("ifcfg", [physical_bond_name, "BRIDGE"], bridge_bond_name)
        dop.set("ifcfg", [physical_bond_name, "BOOTPROTO"], "none")
        dop.set("ifcfg", [physical_bond_name, "ONBOOT"],
                dop.get("ifcfg", [bridge_bond_name, "ONBOOT"]))
        dop.set("ifcfg", [physical_bond_name, "BONDING_OPTS"], bond_options)

        self.up_progress(10)
        dop.set("modprobe_conf", ["alias", physical_bond_name], "bonding")

        for dev in dev_list:
            if os.path.isfile("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev)):
                copy_file("%s/ifcfg-%s" % (NETWORK_IFCFG_DIR, dev),
                          VENDOR_DATA_BONDING_EVACUATION_DIR)
            if os.path.isfile("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev)):
                move_file("%s/ifcfg-p%s" % (NETWORK_IFCFG_DIR, dev),
                          VENDOR_DATA_BONDING_EVACUATION_DIR)

        if ifcfg_parser.write_conf(dop.getconf("ifcfg")) is False:
            raise KssCommandException('Failure write network config file.')

        if modprobe_parser.write_conf(dop.getconf("modprobe_conf")) is False:
            raise KssCommandException('Failure write modprobe config file.')

        self.up_progress(10)
        #
        # Delete bridge device
        #
        bridge_list = get_bridge_info()
        for dev in dev_list:
            if dev in bridge_list:
                ifdown_cmd = (
                    NETWORK_IFDOWN_COMMAND,
                    dev,
                )
                (ifdown_rc, ifdown_res) = execute_command(ifdown_cmd)
                if ifdown_rc != 0:
                    raise KssCommandException(
                        'Failure stop interface. interface:%s' % (dev))

                for brif in bridge_list[dev]:
                    brctl_delif_cmd = (
                        NETWORK_BRCTL_COMMAND,
                        "delif",
                        dev,
                        brif,
                    )
                    (brctl_rc, brctl_res) = execute_command(brctl_delif_cmd)
                    if brctl_rc != 0:
                        raise KssCommandException(
                            'Failure delete bridge port. bridge:%s port:%s' %
                            (dev, brif))

                brctl_delbr_cmd = (
                    NETWORK_BRCTL_COMMAND,
                    "delbr",
                    dev,
                )
                (brctl_rc, brctl_res) = execute_command(brctl_delbr_cmd)
                if brctl_rc != 0:
                    raise KssCommandException(
                        'Failure delete bridge. bridge:%s' % (dev, brif))

        self.up_progress(10)
        #
        # Restart network
        #
        network_restart_cmd = (
            NETWORK_COMMAND,
            "restart",
        )
        (net_rc, net_res) = execute_command(network_restart_cmd)
        if net_rc != 0:
            raise KssCommandException('Failure restart network.')

        self.logger.info("Created bonding device. - dev=%s bond=%s" %
                         (opts.dev, bridge_bond_name))
        print >> sys.stdout, _("Created bonding device. - dev=%s bond=%s" %
                               (opts.dev, bridge_bond_name))

        return True
Example #21
0
def validates_host_edit(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if not is_param(obj.input, 'm_name'):
        check = False
        checker.add_error(_('Parameter m_name does not exist.'))
    else:
        check = checker.check_string(
            _('Machine Name'),
            obj.input.m_name,
            CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE,
            None,
            min=MACHINE_NAME_MIN_LENGTH,
            max=MACHINE_NAME_MAX_LENGTH,
        ) and check

    if not is_param(obj.input, 'm_connect_type'):
        check = False
        checker.add_error(_('Parameter m_connect_type does not exist.'))
    else:
        if obj.input.m_connect_type == "karesansui":

            if not is_param(obj.input, 'm_hostname'):
                check = False
                checker.add_error(_('"%s" is required.') % _('FQDN'))
            else:
                m_hostname_parts = obj.input.m_hostname.split(":")
                if len(m_hostname_parts) > 2:
                    check = False
                    checker.add_error(
                        _('%s contains too many colon(:)s.') % _('FQDN'))
                else:
                    check = checker.check_domainname(
                        _('FQDN'),
                        m_hostname_parts[0],
                        CHECK_EMPTY | CHECK_LENGTH | CHECK_VALID,
                        min=FQDN_MIN_LENGTH,
                        max=FQDN_MAX_LENGTH,
                    ) and check
                    try:
                        check = checker.check_number(
                            _('Port Number'),
                            m_hostname_parts[1],
                            CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX,
                            PORT_MIN_NUMBER,
                            PORT_MAX_NUMBER,
                        ) and check
                    except IndexError:
                        # when reach here, 'm_hostname' has only host name
                        pass

        if obj.input.m_connect_type == "libvirt":

            if not is_param(obj.input, 'm_uri'):
                check = False
                checker.add_error(_('"%s" is required.') % _('URI'))
            else:
                pass

            if is_param(obj.input,
                        'm_auth_user') and obj.input.m_auth_user != "":

                check = checker.check_username(
                    _('User Name'),
                    obj.input.m_auth_user,
                    CHECK_LENGTH | CHECK_ONLYSPACE,
                    min=USER_MIN_LENGTH,
                    max=USER_MAX_LENGTH,
                ) and check

    if is_param(obj.input, 'note_title'):
        check = checker.check_string(
            _('Title'),
            obj.input.note_title,
            CHECK_LENGTH | CHECK_ONLYSPACE,
            None,
            min=NOTE_TITLE_MIN_LENGTH,
            max=NOTE_TITLE_MAX_LENGTH,
        ) and check

    if is_param(obj.input, 'note_value'):
        check = checker.check_string(
            _('Note'),
            obj.input.note_value,
            CHECK_ONLYSPACE,
            None,
            None,
            None,
        ) and check

    if is_param(obj.input, 'tags'):
        for tag in comma_split(obj.input.tags):
            check = checker.check_string(
                _('Tag'),
                tag,
                CHECK_LENGTH | CHECK_ONLYSPACE,
                None,
                min=TAG_MIN_LENGTH,
                max=TAG_MAX_LENGTH,
            ) and check

    obj.view.alert = checker.errors
    return check
Example #22
0
def validates_guest_add(obj):
    checker = Checker()
    check = True

    _ = obj._
    checker.errors = []

    if not is_param(obj.input, 'm_name'):
        check = False
        checker.add_error(_('Parameter m_name does not exist.'))
    else:
        check = checker.check_string(
                    _('Machine Name'),
                    obj.input.m_name,
                    CHECK_EMPTY | CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = MACHINE_NAME_MIN_LENGTH,
                    max = MACHINE_NAME_MAX_LENGTH,
            ) and check

    if is_param(obj.input, 'note_title'):
        check = checker.check_string(
                    _('Title'),
                    obj.input.note_title,
                    CHECK_LENGTH | CHECK_ONLYSPACE,
                    None,
                    min = NOTE_TITLE_MIN_LENGTH,
                    max = NOTE_TITLE_MAX_LENGTH,
                ) and check

    if is_param(obj.input, 'note_value'):
        check = checker.check_string(
                    _('Note'),
                    obj.input.note_value,
                    CHECK_ONLYSPACE,
                    None,
                    None,
                    None,
                ) and check

    if is_param(obj.input, 'tags'):
        for tag in comma_split(obj.input.tags):
            check = checker.check_string(
                        _('Tag'),
                        tag,
                        CHECK_LENGTH | CHECK_ONLYSPACE,
                        None,
                        min = TAG_MIN_LENGTH,
                        max = TAG_MAX_LENGTH,
                    ) and check


    if not is_param(obj.input, 'm_hypervisor'):
        check = False
        checker.add_error(_('Parameter m_hypervisor does not exist.'))
    else:
        check = checker.check_hypervisor(
                _('Hypervisor'),
                obj.input.m_hypervisor,
                CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX,
                HYPERVISOR_MIN_SIZE,
                HYPERVISOR_MAX_SIZE,
            ) and check

    if not is_param(obj.input, 'domain_name'):
        check = False
        checker.add_error(_('Parameter domain_name does not exist.'))
    else:
        check = checker.check_string(
                _('Domain Name'),
                obj.input.domain_name,
                CHECK_EMPTY | CHECK_VALID | CHECK_LENGTH | CHECK_ONLYSPACE,
                '[^-a-zA-Z0-9_\.]+',
                DOMAIN_NAME_MIN_LENGTH,
                DOMAIN_NAME_MAX_LENGTH,
            ) and check

        if obj.input.domain_name in get_dom_list():
            dom_type = get_dom_type(obj.input.domain_name)
            checker.add_error(_("The same domain name already exists for hypervisor '%s'.") % dom_type.upper())
            check = False

    if is_param(obj.input, 'vm_mem_size'):
        check = checker.check_number(
                _('Memory Size (MB)'),
                obj.input.vm_mem_size,
                CHECK_VALID | CHECK_MIN | CHECK_EMPTY,
                MEMORY_MIN_SIZE,
                None,
            ) and check

    if is_param(obj.input, 'pool_type'):
        if obj.input.pool_type != "block":
            if is_param(obj.input, 'vm_disk_size'):
                check = checker.check_number(
                        _('Disk Size (MB)'),
                        obj.input.vm_disk_size,
                        CHECK_VALID | CHECK_MIN | CHECK_EMPTY,
                        DISK_MIN_SIZE,
                        None,
                ) and check

    if not is_param(obj.input, 'boot_image'):
        check = False
        checker.add_error(_('Parameter boot_image does not exist.'))
    else:
        if obj.input.boot_image == "kernel":
            if not is_param(obj.input, 'vm_kernel'):
                check = False
                checker.add_error(_('Parameter vm_kernel does not exist.'))
            else:
                check = checker.check_startfile(
                        _('Kernel Image'),
                        obj.input.vm_kernel,
                        CHECK_EMPTY | CHECK_VALID | CHECK_EXIST,
                    ) and check

            if not is_param(obj.input, 'vm_initrd'):
                check = False
                checker.add_error(_('Parameter vm_initrd does not exist.'))
            else:
                check = checker.check_startfile(
                        _('Initrd Image'),
                        obj.input.vm_initrd,
                        CHECK_EMPTY | CHECK_VALID | CHECK_EXIST,
                    ) and check

        if obj.input.boot_image == "iso":
            if not is_param(obj.input, 'vm_iso'):
                check = False
                checker.add_error(_('Parameter vm_iso does not exist.'))
            else:
                check = checker.check_startfile(
                        _('ISO Image'),
                        obj.input.vm_iso,
                        CHECK_EMPTY | CHECK_VALID | CHECK_EXIST,
                    ) and check
                if check:
                    check = is_iso9660_filesystem_format(obj.input.vm_iso)
                    checker.add_error(_('"%s" is not valid ISO 9660 CD-ROM filesystem data.') % obj.input.vm_iso)

    if not is_param(obj.input, 'keymap'):
        check = False
        checker.add_error(_('"%s" is required.') % _('Graphics Keymap'))
    else:
        hypervisor = "KVM"
        if int(obj.input.m_hypervisor) == MACHINE_HYPERVISOR['XEN']:
            hypervisor = "XEN"
        elif int(obj.input.m_hypervisor) == MACHINE_HYPERVISOR['KVM']:
            hypervisor = "KVM"
        check = checker.check_keymap(
                _('Graphics Keymap'),
                obj.input.keymap,
                CHECK_EMPTY | CHECK_EXIST,
                hypervisor
                ) and check

    if not is_param(obj.input, 'vm_graphics_port'):
        check = False
        checker.add_error(_('Parameter vm_graphics_port does not exist.'))
    else:
        check = checker.check_number(
                _('Graphics Port Number'),
                obj.input.vm_graphics_port,
                CHECK_EMPTY | CHECK_VALID | CHECK_MIN | CHECK_MAX,
                GRAPHICS_PORT_MIN_NUMBER,
                GRAPHICS_PORT_MAX_NUMBER,
            ) and check

    if not is_param(obj.input, 'vm_mac'):
        check = False
        checker.add_error(_('Parameter vm_mac does not exist.'))
    else:
        check = checker.check_macaddr(
                _('MAC Address'),
                obj.input.vm_mac,
                CHECK_EMPTY | CHECK_VALID,
            ) and check

    obj.view.alert = checker.errors
    return check
Example #23
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
Example #24
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