Exemplo n.º 1
0
    def test_create_from_xml(self):
        uuid = randomUUID()
        xml = self.xml.replace('test-vm', 'test-vm-xml')
        xml = re.sub('\s?<uuid>.*?</uuid>', f'<uuid>{uuid}</uuid>', xml)
        response = self.client.post(
            reverse('instances:create_instance_select_type',
                    args=[self.compute.id]),
            {
                'create_xml': True,
                'dom_xml': xml,
            },
        )
        self.assertEqual(response.status_code, 302)

        xml_instance_qs: Instance = Instance.objects.filter(name='test-vm-xml')
        self.assertEqual(len(xml_instance_qs), 1)

        xml_instance = xml_instance_qs[0]

        # destroy started instance to maximize coverage
        xml_instance.proxy.start()

        response = self.client.post(
            reverse('instances:destroy', args=[xml_instance.id]),
            {},  # do not delete disk image
            HTTP_REFERER=reverse('index'),
        )
        self.assertRedirects(response, reverse('instances:index'))
Exemplo n.º 2
0
    def do_execute(self, quick_model: create_models.QuickVM):
        vcpu_num = quick_model.vcpu
        memory = quick_model.memory
        clock = quick_model.clock
        network = quick_model.network
        if not quick_model.disks_path:
            raise Exception('no disk')

        compute = compute_models.Compute.objects.get(id=quick_model.compute_id)
        conn = wvmCreate(compute.hostname, compute.login, compute.password,
                         compute.type)
        uuid = util.randomUUID()
        #path = conn.get_volume_path(vol)
        #volumes[path] = conn.get_volume_type(path)
        disks = quick_model.disks_path.split(',')

        volumes = {}
        for disk_path in disks:
            volumes[disk_path] = conn.get_volume_type(disk_path)

        data = {
            'uuid': uuid,
            'name': quick_model.token,
            'memory': memory,
            'vcpu': vcpu_num,
            'images': volumes,
            'host_model': True,
            'cache_mode': 'default',
            'networks': network,
            'virtio': True,
            'clock': clock,
        }
        console_type = quick_model.console_type
        video_mode = quick_model.video_mode
        conn.create_instance(**data,
                             console_type=console_type,
                             video_model=video_mode)
        create_instance = Instance(compute_id=quick_model.compute_id,
                                   name=data['name'],
                                   uuid=uuid)
        create_instance.save()
        quick_model.instance = create_instance
        quick_model.save()
Exemplo n.º 3
0
def create(request, host_id):
    """
    Create new instance.
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    conn = None
    errors = []
    storages = []
    networks = []
    meta_prealloc = False
    compute = Compute.objects.get(id=host_id)
    flavors = Flavor.objects.filter().order_by('id')

    try:
        conn = wvmCreate(compute.hostname,
                         compute.login,
                         compute.password,
                         compute.type)

        storages = sorted(conn.get_storages())
        networks = sorted(conn.get_networks())
        instances = conn.get_instances()
        get_images = sorted(conn.get_storages_images())
        cache_modes = sorted(conn.get_cache_modes().items())
        mac_auto = util.randomMAC()
    except libvirtError as err:
        errors.append(err)

    if conn:
        if not storages:
            msg = _("You haven't defined have any storage pools")
            errors.append(msg)
        if not networks:
            msg = _("You haven't defined have any network pools")
            errors.append(msg)

        if request.method == 'POST':
            if 'create_flavor' in request.POST:
                form = FlavorAddForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    create_flavor = Flavor(label=data['label'],
                                           vcpu=data['vcpu'],
                                           memory=data['memory'],
                                           disk=data['disk'])
                    create_flavor.save()
                    return HttpResponseRedirect(request.get_full_path())
            if 'delete_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                delete_flavor = Flavor.objects.get(id=flavor_id)
                delete_flavor.delete()
                return HttpResponseRedirect(request.get_full_path())
            if 'create_xml' in request.POST:
                xml = request.POST.get('from_xml', '')
                try:
                    name = util.get_xml_path(xml, '/domain/name')
                except util.libxml2.parserError:
                    name = None
                if name in instances:
                    msg = _("A virtual machine with this name already exists")
                    errors.append(msg)
                else:
                    try:
                        conn._defineXML(xml)
                        return HttpResponseRedirect(reverse('instance', args=[host_id, name]))
                    except libvirtError as err:
                        errors.append(err.message)
            if 'create' in request.POST:
                volumes = {}
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if data['meta_prealloc']:
                        meta_prealloc = True
                    if instances:
                        if data['name'] in instances:
                            msg = _("A virtual machine with this name already exists")
                            errors.append(msg)
                    if not errors:
                        if data['hdd_size']:
                            if not data['mac']:
                                msg = _("No Virtual Machine MAC has been entered")
                                errors.append(msg)
                            else:
                                try:
                                    path = conn.create_volume(data['storage'], data['name'], data['hdd_size'],
                                                              metadata=meta_prealloc)
                                    volumes[path] = conn.get_volume_type(path)
                                except libvirtError as msg_error:
                                    errors.append(msg_error.message)
                        elif data['template']:
                            templ_path = conn.get_volume_path(data['template'])
                            clone_path = conn.clone_from_template(data['name'], templ_path, metadata=meta_prealloc)
                            volumes[clone_path] = conn.get_volume_type(clone_path)
                        else:
                            if not data['images']:
                                msg = _("First you need to create or select an image")
                                errors.append(msg)
                            else:
                                for vol in data['images'].split(','):
                                    try:
                                        path = conn.get_volume_path(vol)
                                        volumes[path] = conn.get_volume_type(path)
                                    except libvirtError as msg_error:
                                        errors.append(msg_error.message)
                        if data['cache_mode'] not in conn.get_cache_modes():
                            msg = _("Invalid cache mode")
                            errors.append(msg)
                        if not errors:
                            uuid = util.randomUUID()
                            try:
                                conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'],
                                                     uuid, volumes, data['cache_mode'], data['networks'], data['virtio'],
                                                     data['mac'])
                                create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid)
                                create_instance.save()
                                return HttpResponseRedirect(reverse('instance', args=[host_id, data['name']]))
                            except libvirtError as err:
                                if data['hdd_size']:
                                    conn.delete_volume(volumes.keys()[0])
                                errors.append(err)

        conn.close()

    return render_to_response('create.html', locals(), context_instance=RequestContext(request))
Exemplo n.º 4
0
def create(request, host_id):
    """
    Create new instance.
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    conn = None
    errors = []
    storages = []
    networks = []
    meta_prealloc = False
    compute = Compute.objects.get(id=host_id)
    flavors = Flavor.objects.filter().order_by('id')

    try:
        conn = wvmCreate(compute.hostname,
                         compute.login,
                         compute.password,
                         compute.type)

        storages = sorted(conn.get_storages())
        networks = sorted(conn.get_networks())
        instances = conn.get_instances()
        get_images = sorted(conn.get_storages_images())
        mac_auto = util.randomMAC()
    except libvirtError as err:
        errors.append(err)

    if conn:
        if not storages:
            msg = _("You haven't defined have any storage pools")
            errors.append(msg)
        if not networks:
            msg = _("You haven't defined have any network pools")
            errors.append(msg)

        if request.method == 'POST':
            if 'create_flavor' in request.POST:
                form = FlavorAddForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    create_flavor = Flavor(label=data['label'],
                                           vcpu=data['vcpu'],
                                           memory=data['memory'],
                                           disk=data['disk'])
                    create_flavor.save()
                    return HttpResponseRedirect(request.get_full_path())
            if 'delete_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                delete_flavor = Flavor.objects.get(id=flavor_id)
                delete_flavor.delete()
                return HttpResponseRedirect(request.get_full_path())
            if 'create_xml' in request.POST:
                xml = request.POST.get('from_xml', '')
                try:
                    name = util.get_xml_path(xml, '/domain/name')
                except util.libxml2.parserError:
                    name = None
                if name in instances:
                    msg = _("A virtual machine with this name already exists")
                    errors.append(msg)
                else:
                    try:
                        conn._defineXML(xml)
                        return HttpResponseRedirect(reverse('instance', args=[host_id, name]))
                    except libvirtError as err:
                        errors.append(err.message)
            if 'create' in request.POST:
                volumes = {}
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if data['meta_prealloc']:
                        meta_prealloc = True
                    if instances:
                        if data['name'] in instances:
                            msg = _("A virtual machine with this name already exists")
                            errors.append(msg)
                    if not errors:
                        if data['hdd_size']:
                            if not data['mac']:
                                msg = _("No Virtual Machine MAC has been entered")
                                errors.append(msg)
                            else:
                                try:
                                    path = conn.create_volume(data['storage'], data['name'], data['hdd_size'],
                                                              metadata=meta_prealloc)
                                    volumes[path] = conn.get_volume_type(path)
                                except libvirtError as msg_error:
                                    errors.append(msg_error.message)
                        elif data['template']:
                            templ_path = conn.get_volume_path(data['template'])
                            clone_path = conn.clone_from_template(data['name'], templ_path, metadata=meta_prealloc)
                            volumes[clone_path] = conn.get_volume_type(clone_path)
                        else:
                            if not data['images']:
                                msg = _("First you need to create or select an image")
                                errors.append(msg)
                            else:
                                for vol in data['images'].split(','):
                                    try:
                                        path = conn.get_volume_path(vol)
                                        volumes[path] = conn.get_volume_type(path)
                                    except libvirtError as msg_error:
                                        errors.append(msg_error.message)
                        if not errors:
                            uuid = util.randomUUID()
                            try:
                                conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'],
                                                     uuid, volumes, data['networks'], data['virtio'], data['mac'])
                                create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid)
                                create_instance.save()
                                return HttpResponseRedirect(reverse('instance', args=[host_id, data['name']]))
                            except libvirtError as err:
                                if data['hdd_size']:
                                    conn.delete_volume(volumes.keys()[0])
                                errors.append(err)

        conn.close()

    return render_to_response('create.html', locals(), context_instance=RequestContext(request))
Exemplo n.º 5
0
def create_instance(request, compute_id):
    """
    :param request:
    :return:
    """

    if not request.user.is_superuser:
        return HttpResponseRedirect(reverse('index'))

    conn = None
    error_messages = []
    storages = []
    networks = []
    meta_prealloc = False
    compute = get_object_or_404(Compute, pk=compute_id)
    flavors = Flavor.objects.filter().order_by('id')

    try:
        conn = wvmCreate(compute.hostname, compute.login, compute.password,
                         compute.type)

        storages = sorted(conn.get_storages(only_actives=True))
        networks = sorted(conn.get_networks())
        nwfilters = conn.get_nwfilters()
        instances = conn.get_instances()
        videos = conn.get_video()
        cache_modes = sorted(conn.get_cache_modes().items())
        default_cache = INSTANCE_VOLUME_DEFAULT_CACHE
        listener_addr = QEMU_CONSOLE_LISTEN_ADDRESSES
        mac_auto = util.randomMAC()
        disk_devices = conn.get_disk_device_types()
        disk_buses = conn.get_disk_bus_types()
        default_bus = INSTANCE_VOLUME_DEFAULT_BUS
    except libvirtError as lib_err:
        error_messages.append(lib_err)

    if conn:
        if not storages:
            msg = _("You haven't defined any storage pools")
            error_messages.append(msg)
        if not networks:
            msg = _("You haven't defined any network pools")
            error_messages.append(msg)

        if request.method == 'POST':
            if 'create_flavor' in request.POST:
                form = FlavorAddForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    create_flavor = Flavor(label=data['label'],
                                           vcpu=data['vcpu'],
                                           memory=data['memory'],
                                           disk=data['disk'])
                    create_flavor.save()
                    return HttpResponseRedirect(request.get_full_path())
            if 'delete_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                delete_flavor = Flavor.objects.get(id=flavor_id)
                delete_flavor.delete()
                return HttpResponseRedirect(request.get_full_path())
            if 'create_xml' in request.POST:
                xml = request.POST.get('dom_xml', '')
                try:
                    name = util.get_xml_path(xml, '/domain/name')
                except util.etree.Error as err:
                    name = None
                if name in instances:
                    error_msg = _(
                        "A virtual machine with this name already exists")
                    error_messages.append(error_msg)
                else:
                    try:
                        conn._defineXML(xml)
                        return HttpResponseRedirect(
                            reverse('instance', args=[compute_id, name]))
                    except libvirtError as lib_err:
                        error_messages.append(lib_err.message)
            if 'create' in request.POST:
                volume_list = []

                clone_path = ""
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if data['meta_prealloc']:
                        meta_prealloc = True
                    if instances:
                        if data['name'] in instances:
                            msg = _(
                                "A virtual machine with this name already exists"
                            )
                            error_messages.append(msg)
                        if Instance.objects.filter(name__exact=data['name']):
                            messages.warning(
                                request,
                                _("There is an instance with same name. Are you sure?"
                                  ))
                    if not error_messages:
                        if data['hdd_size']:
                            if not data['mac']:
                                error_msg = _(
                                    "No Virtual Machine MAC has been entered")
                                error_messages.append(error_msg)
                            else:
                                try:
                                    path = conn.create_volume(
                                        data['storage'],
                                        data['name'],
                                        data['hdd_size'],
                                        metadata=meta_prealloc)
                                    volume = dict()
                                    volume['path'] = path
                                    volume['type'] = conn.get_volume_type(path)
                                    volume['device'] = 'disk'
                                    volume['bus'] = 'virtio'
                                    volume_list.append(volume)
                                except libvirtError as lib_err:
                                    error_messages.append(lib_err.message)
                        elif data['template']:
                            templ_path = conn.get_volume_path(data['template'])
                            dest_vol = conn.get_volume_path(
                                data["name"] + ".img", data['storage'])
                            if dest_vol:
                                error_msg = _(
                                    "Image has already exist. Please check volumes or change instance name"
                                )
                                error_messages.append(error_msg)
                            else:
                                clone_path = conn.clone_from_template(
                                    data['name'],
                                    templ_path,
                                    data['storage'],
                                    metadata=meta_prealloc)
                                volume = dict()
                                volume['path'] = clone_path
                                volume['type'] = conn.get_volume_type(
                                    clone_path)
                                volume['device'] = 'disk'
                                volume['bus'] = 'virtio'
                                volume_list.append(volume)
                        else:
                            if not data['images']:
                                error_msg = _(
                                    "First you need to create or select an image"
                                )
                                error_messages.append(error_msg)
                            else:
                                for idx, vol in enumerate(
                                        data['images'].split(',')):
                                    try:

                                        path = conn.get_volume_path(vol)
                                        volume = dict()
                                        volume['path'] = path
                                        volume['type'] = conn.get_volume_type(
                                            path)
                                        volume['device'] = request.POST.get(
                                            'device' + str(idx), '')
                                        volume['bus'] = request.POST.get(
                                            'bus' + str(idx), '')
                                        volume_list.append(volume)
                                    except libvirtError as lib_err:
                                        error_messages.append(lib_err.message)
                        if data['cache_mode'] not in conn.get_cache_modes():
                            error_msg = _("Invalid cache mode")
                            error_messages.append(error_msg)
                        if not error_messages:
                            uuid = util.randomUUID()
                            try:
                                conn.create_instance(
                                    data['name'], data['memory'], data['vcpu'],
                                    data['host_model'], uuid, volume_list,
                                    data['cache_mode'], data['networks'],
                                    data['virtio'], data["listener_addr"],
                                    data["nwfilter"], data["video"],
                                    data["console_pass"], data['mac'],
                                    data['qemu_ga'])
                                create_instance = Instance(
                                    compute_id=compute_id,
                                    name=data['name'],
                                    uuid=uuid)
                                create_instance.save()
                                msg = _("Instance is created.")
                                messages.success(request, msg)
                                addlogmsg(request.user.username,
                                          create_instance.name, msg)
                                return HttpResponseRedirect(
                                    reverse('instance',
                                            args=[compute_id, data['name']]))
                            except libvirtError as lib_err:
                                if data['hdd_size'] or volume_list.count() > 0:
                                    for vol in volume_list:
                                        conn.delete_volume(vol['path'])
                                error_messages.append(lib_err)
        conn.close()
    return render(request, 'create_instance.html', locals())
Exemplo n.º 6
0
def create(request, host_id):
    """
    Create new instance.
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    conn = None
    errors = []
    ifaces_all = []
    ifaces_all_name = ""
    storages = []
    hd_resources = {}
    meta_prealloc = False
    compute = Compute.objects.get(id=host_id)
    flavors = Flavor.objects.filter().order_by('id')
    flavor_name_list = Flavor.objects.filter(label='label')
    memory_range = [2048, 4096, 6144, 8192, 16384]
    vcpu_range = None

    try:
        conn = wvmCreate(compute.hostname,
                         compute.login,
                         compute.password,
                         compute.type)
        conn_interfaces = wvmInterfaces(compute.hostname,
                             compute.login,
                             compute.password,
                             compute.type)
        ifaces = conn_interfaces.get_ifaces()
        storages = sorted(conn.get_storages())
        instances = conn.get_instances()
        get_images = sorted(conn.get_storages_images())

        if os.path.exists(util.get_hd_resources_conf()):
            hd_resources = util.load_hd_resources()
            mem_left = hd_resources["mem"]
            vcpu_left = hd_resources["vcpu"]
            hd_resources = util.filter_hd_resources(hd_resources)
        else:
            hd_resources = util.create_hd_resources()
            mem_left = hd_resources["mem"]
            vcpu_left = hd_resources["vcpu"]
            hd_resources = util.filter_hd_resources(hd_resources)
        memory_range = [ memory for memory in memory_range if memory/1024 <= mem_left ]
        vcpu_range = xrange(1, int(vcpu_left) + 1)

    except libvirtError as err:
        errors.append(err)

    if conn_interfaces:
        try:
            netdevs = conn_interfaces.get_net_device()
        except:
            netdevs = ['eth0', 'eth1'] 

    if conn:
        if not storages:
            msg = _("You haven't defined have any storage pools")
            errors.append(msg)

        if request.method == 'POST':
            if 'create_flavor' in request.POST:
                form = FlavorAddForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    flavor_name_list = Flavor.objects.filter(label=data['label'])
                    if flavor_name_list:
                        msg = _("A virtual machine template with this name already exists")
                        errors.append(msg)
                    else:
                        create_flavor = Flavor(label=data['label'],
                                           vcpu=data['vcpu'],
                                           memory=data['memory'],
                                           disk=data['disk'])
                        create_flavor.save()
                        return HttpResponseRedirect(request.get_full_path())
            if 'delete_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                delete_flavor = Flavor.objects.get(id=flavor_id)
                delete_flavor.delete()
                return HttpResponseRedirect(request.get_full_path())
            if 'create_xml' in request.POST:
                xml = request.POST.get('from_xml', '')
                try:
                    name = util.get_xml_path(xml, '/domain/name')
                except util.libxml2.parserError:
                    name = None
                if name in instances:
                    msg = _("A virtual machine with this name already exists")
                    errors.append(msg)
                else:
                    try:
                        conn._defineXML(xml)
                        return HttpResponseRedirect(reverse('instance', args=[host_id, name]))
                    except libvirtError as err:
                        errors.append(err.message)
            if 'create' in request.POST:
                
                volumes = {}
                interfaces = []
                vm_vfs_info = {}
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if instances:
                        if data['name'] in instances:
                            msg = _("A virtual machine with this name already exists")
                            errors.append(msg)
                    if not errors:
                        
                        if data['hdd_size']:
                            try:
                                path = conn.create_volume(data['storage'], data['name'], data['hdd_size'],
                                                          metadata=meta_prealloc)
                                volumes[path] = conn.get_volume_type(path)
                            except libvirtError as msg_error:
                                errors.append(msg_error.message)
                        elif data['template']:
                            templ_path = conn.get_volume_path(data['template'])
                            clone_path = conn.clone_from_template(data['name'], templ_path, metadata=meta_prealloc)
                            volumes[clone_path] = conn.get_volume_type(clone_path)

                            ifaces_all = request.POST.getlist('interfaces')
                        else:
                            if not data['images']:
                                msg = _("First you need to create or select an image")
                                errors.append(msg)
                            else:
                                for vol in data['images'].split(','):
                                    try:
                                        path = conn.get_volume_path(vol)
                                        volumes[path] = conn.get_volume_type(path)
                                    except libvirtError as msg_error:
                                        errors.append(msg_error.message)
                            
                        if not errors:
                            uuid = util.randomUUID()
                            try:
                                template_ver3_flag = True
                                if data['template'].find("WiseGrid_V3") == -1:
                                    template_ver3_flag = False

                                conn.create_instance(data['name'], data['cur_memory'], data['cur_vcpu'], 
                                                     uuid, volumes, ifaces_all, False, True, template_ver3_flag)
                                create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid)
                                create_instance.save()
                                vm_vfs_info[data['name']] = ifaces_all
                                if not errors:
                                   util.update_vfs_fro_vm(vm_vfs_info)
                                return HttpResponseRedirect(reverse('instance', args=[host_id, data['name']]))
                            except libvirtError as err:
                                if data['hdd_size']:
                                    conn.delete_volume(volumes.keys()[0])
                                errors.append(err)
                else:
                    print form.errors
                    errors.append(form.errors)
        conn.close()
        return HttpResponseRedirect(reverse('instances',args=[host_id,errors]))
Exemplo n.º 7
0
def instances(request, host_id):
    """
    Instances block
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    errors = []
    instances = []
    time_refresh = 8000
    get_instances = []
    cnt_max = settings.vf_cnt_max
    conn = None
    meta_prealloc = False
    compute = Compute.objects.get(id=host_id)
    memory_range = [2048, 4096, 6144, 8192, 16384]
    ifaces_all = util.get_free_vfs()
    ifaces_all = sorted(ifaces_all.iteritems(),key=lambda ax:ax[0])

    try:
        conn = wvmInstances(compute.hostname,
                            compute.login,
                            compute.password,
                            compute.type)
        conn_create = wvmCreate(compute.hostname,
                         compute.login,
                         compute.password,
                         compute.type)
        conn_storage = wvmStorage(compute.hostname,
                          compute.login,
                          compute.password,
                          compute.type,
                          'Images')
        state = conn_storage.is_active()
        if state:
            conn_storage.refresh()
            volumes = conn_storage.update_volumes()
            conn_storage.close()
        else:
            volumes = None
        get_images = volumes
        get_instances = conn.get_instances()
    except libvirtError as err:
        pass
#        errors.append(err)

    for instance in get_instances:
        try:
            inst = Instance.objects.get(compute_id=host_id, name=instance)
            uuid = inst.uuid
        except Instance.DoesNotExist:
            uuid = conn.get_uuid(instance)
            inst = Instance(compute_id=host_id, name=instance, uuid=uuid)
            inst.save()
        instances.append({'name': instance,
                          'status': conn.get_instance_status(instance),
                          'uuid': uuid,
                          'memory': conn.get_instance_memory(instance),
                          'vcpu': conn.get_instance_vcpu(instance),
                          'has_managed_save_image': conn.get_instance_managed_save_image(instance)})
    if conn:
        try:
            if request.method == 'POST':
                name = request.POST.get('name', '')
                if 'start' in request.POST:
                    conn.start(name)
                    return HttpResponseRedirect(request.get_full_path())
                if 'shutdown' in request.POST:
                    conn.shutdown(name)
                    return HttpResponseRedirect(request.get_full_path())
                if 'destroy' in request.POST:
                    conn.force_shutdown(name)
                    return HttpResponseRedirect(request.get_full_path())
                if 'managedsave' in request.POST:
                    conn.managedsave(name)
                    return HttpResponseRedirect(request.get_full_path())
                if 'deletesaveimage' in request.POST:
                    conn.managed_save_remove(name)
                    return HttpResponseRedirect(request.get_full_path())
                if 'suspend' in request.POST:
                    conn.suspend(name)
                    return HttpResponseRedirect(request.get_full_path())
                if 'resume' in request.POST:
                    conn.resume(name)
                    return HttpResponseRedirect(request.get_full_path())
                if 'create' in request.POST:
                
                    volumes = {}
                    interfaces = []
                    vm_vfs_info = {}
                    form = NewVMForm(request.POST)
                    if form.is_valid():
                        data = form.cleaned_data
                        if instances:
                            if data['name'] in instances:
                                msg = _("A virtual machine with this name already exists")
                                errors.append(msg)
                        if not errors:
                        
                            if data['hdd_size']:
                                try:
                                    path = conn.create_volume(data['storage'], data['name'], data['hdd_size'],
                                                          metadata=meta_prealloc)
                                    volumes[path] = conn.get_volume_type(path)
                                except libvirtError as msg_error:
                                    errors.append(msg_error.message)
                            elif data['template']:
                                templ_path = conn_create.get_volume_path(data['template'])
                                clone_path = conn_create.clone_from_template(data['name'], templ_path, metadata=meta_prealloc)
                                volumes[clone_path] = conn_create.get_volume_type(clone_path)

                                ifaces_all = request.POST.getlist('interfaces')
                            else:
                                if not data['images']:
                                    msg = _("First you need to create or select an image")
                                    errors.append(msg)
                                else:
                                    for vol in data['images'].split(','):
                                        try:
                                            path = conn.get_volume_path(vol)
                                            volumes[path] = conn.get_volume_type(path)
                                        except libvirtError as msg_error:
                                            errors.append(msg_error.message)
                            
                            if not errors:
                                uuid = util.randomUUID()
                                try:
                                    template_ver3_flag = True
                                    if data['template'].find("WiseGrid_V3") == -1:
                                        template_ver3_flag = False

                                    conn_create.create_instance(data['name'], data['cur_memory'], data['cur_vcpu'], 
                                                     uuid, volumes, ifaces_all, False, True, template_ver3_flag)
                                    create_instance = Instance(compute_id=host_id, name=data['name'], uuid=uuid)
                                    create_instance.save()
                                    vm_vfs_info[data['name']] = ifaces_all
                                    if not errors:
                                       util.update_vfs_fro_vm(vm_vfs_info)
                                    return HttpResponseRedirect(reverse('instance', args=[host_id, data['name']]))
                                except libvirtError as err:
                                    if data['hdd_size']:
                                        conn_create.delete_volume(volumes.keys()[0])
                                    errors.append(err)
                    else:
                        print form.errors
                        errors.append(form.errors)
            conn.close()
            conn_create.close()
        except libvirtError as err:
            errors.append(err)
        hd_resources = util.load_hd_resources()
        mem_left = hd_resources["mem"]
        vcpu_left = hd_resources["vcpu"]
        memory_range = [ memory for memory in memory_range if memory/1024 <= mem_left ]
        vcpu_range = xrange(1, int(vcpu_left) + 1)
        vcpu_memory_left_flag = True
        if len(list(vcpu_range)) == 0 or len(memory_range) == 0:
            vcpu_memory_left_flag = False
         
    return render_to_response('instances.html', locals(), context_instance=RequestContext(request))
Exemplo n.º 8
0
def createlxc(request, host_id):
    """
    Create new lxc container instance.
    """

    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    if not request.user.is_staff:
        raise PermissionDenied

    conn = None
    errors = []
    storages = []
    networks = []
    compute = Compute.objects.get(id=host_id)
    instances = None
    wmstorage =None
    templatedb = {}
    templatelist = []
    with open('/var/www/webvirtmgr/ansiblefunc/playbook/template','r') as template:
        lines = template.readlines()
        for line in lines:
            templatedb[line.split(',')[0]] = line.split(',')[1].strip()
            templatelist.append(line.split(',')[0])
    try:
        conn = wvmCreate(compute.hostname,
                         compute.login,
                         compute.password,
                         compute.type,
                         compute.hypervisor)

        storages = sorted(conn.get_storages())
        networks = sorted(conn.get_networks())
        instances = conn.get_instances()
        get_images = sorted(conn.get_storages_images())
        get_containtype = sorted(['operation system','application'])
        mac_auto = util.randomMAC()
    except libvirtError as err:
        errors.append(err)
    if conn:
        if not storages:
            msg = _("You haven't defined have any storage pools")
            errors.append(msg)
        if not networks:
            msg = _("You haven't defined have any network pools")
            errors.append(msg)
        if request.method == 'POST':
            if 'create' in request.POST:
                volumes = {}
                pathtuple=[]
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if data['meta_prealloc']:
                        meta_prealloc = True
                    if data['name'] in instances:
                        msg = _("A virtual machine with this name already exists")
                        errors.append(msg)
                    if not data['images']:
                        msg = _("First you need to create or select an image")
                        errors.append(msg)
                    if not errors:
                        for vol in data['images'].split(','):
                            try:
                                path = conn.get_volume_path(vol)
                                volumes[path] = conn.get_volume_type(path)
                                pathtuple.append(path)
                            except libvirtError as msg_error:
                                errors.append(msg_error.message)
                        if not errors:
                            uuid = util.randomUUID()
                            try:
                                root = data['images'].split(',')[0]
                                print root
                                rootimage = conn.get_volume_path(root)
                                ostype={'os':'/sbin/init','app':'/bin/sh'}
                                if not data['template']:
                                    lxcdeployjob = ansiblefunc.ans_func.AnsDeployJob(vmname=data['name'],memory=data['memory'],rootimage=rootimage,supervisorip=
                                                                      conn.host,network=data['networks'].split(','),inittype=ostype[form.data['containtype']],
                                                                      rootpass=form.data['rootpass'],cpu=form.data['vcpu'],installedpackage=form.data['packages'],
                                                                      images=pathtuple[1:])
                                else:
                                    lxcdeployjob = ansiblefunc.ans_func.AnsDeployJob(vmname=data['name'],
                                                                                     memory=data['memory'],
                                                                                     rootimage=rootimage, supervisorip=
                                                                                     conn.host,
                                                                                     network=data['networks'].split(
                                                                                         ','),
                                                                                     rootpass=form.data['rootpass'],
                                                                                     cpu=form.data['vcpu'],
                                                                                     images=[],
                                                                                     templatename=data['template'])
                                lxcdeployjob.deploy()
                                time.sleep(2)
                                return HttpResponseRedirect(reverse('instances', args=[host_id]))
                            except libvirtError as err:
                                if data['hdd_size']:
                                    conn.delete_volume(volumes.keys()[0])
                                errors.append(err)

    conn.close()
    return render_to_response('createlxc.html', locals(), context_instance=RequestContext(request))
Exemplo n.º 9
0
def create_instance(request, compute_id):
    """
    :param request:
    :return:
    """

    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse("index"))

    if not request.user.is_superuser:
        return HttpResponseRedirect(reverse("index"))

    conn = None
    error_messages = []
    storages = []
    networks = []
    meta_prealloc = False
    computes = Compute.objects.all()
    compute = get_object_or_404(Compute, pk=compute_id)
    flavors = Flavor.objects.filter().order_by("id")

    try:
        conn = wvmCreate(compute.hostname, compute.login, compute.password, compute.type)

        storages = sorted(conn.get_storages())
        networks = sorted(conn.get_networks())
        instances = conn.get_instances()
        get_images = sorted(conn.get_storages_images())
        cache_modes = sorted(conn.get_cache_modes().items())
        mac_auto = util.randomMAC()
    except libvirtError as lib_err:
        error_messages.append(lib_err)

    if conn:
        if not storages:
            msg = _("You haven't defined any storage pools")
            error_messages.append(msg)
        if not networks:
            msg = _("You haven't defined any network pools")
            error_messages.append(msg)

        if request.method == "POST":
            if "create_flavor" in request.POST:
                form = FlavorAddForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    create_flavor = Flavor(
                        label=data["label"], vcpu=data["vcpu"], memory=data["memory"], disk=data["disk"]
                    )
                    create_flavor.save()
                    return HttpResponseRedirect(request.get_full_path())
            if "delete_flavor" in request.POST:
                flavor_id = request.POST.get("flavor", "")
                delete_flavor = Flavor.objects.get(id=flavor_id)
                delete_flavor.delete()
                return HttpResponseRedirect(request.get_full_path())
            if "create_xml" in request.POST:
                xml = request.POST.get("from_xml", "")
                try:
                    name = util.get_xml_path(xml, "/domain/name")
                except util.libxml2.parserError:
                    name = None
                if name in instances:
                    error_msg = _("A virtual machine with this name already exists")
                    error_messages.append(error_msg)
                else:
                    try:
                        conn._defineXML(xml)
                        return HttpResponseRedirect(reverse("instance", args=[compute_id, name]))
                    except libvirtError as lib_err:
                        error_messages.append(lib_err.message)
            if "create" in request.POST:
                volumes = {}
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if data["meta_prealloc"]:
                        meta_prealloc = True
                    if instances:
                        if data["name"] in instances:
                            msg = _("A virtual machine with this name already exists")
                            error_messages.append(msg)
                    if not error_messages:
                        if data["hdd_size"]:
                            if not data["mac"]:
                                error_msg = _("No Virtual Machine MAC has been entered")
                                error_messages.append(error_msg)
                            else:
                                try:
                                    path = conn.create_volume(
                                        data["storage"], data["name"], data["hdd_size"], metadata=meta_prealloc
                                    )
                                    volumes[path] = conn.get_volume_type(path)
                                except libvirtError as lib_err:
                                    error_messages.append(lib_err.message)
                        elif data["template"]:
                            templ_path = conn.get_volume_path(data["template"])
                            clone_path = conn.clone_from_template(data["name"], templ_path, metadata=meta_prealloc)
                            volumes[clone_path] = conn.get_volume_type(clone_path)
                        else:
                            if not data["images"]:
                                error_msg = _("First you need to create or select an image")
                                error_messages.append(error_msg)
                            else:
                                for vol in data["images"].split(","):
                                    try:
                                        path = conn.get_volume_path(vol)
                                        volumes[path] = conn.get_volume_type(path)
                                    except libvirtError as lib_err:
                                        error_messages.append(lib_err.message)
                        if data["cache_mode"] not in conn.get_cache_modes():
                            error_msg = _("Invalid cache mode")
                            error_messages.append(error_msg)
                        if not error_messages:
                            uuid = util.randomUUID()
                            try:
                                conn.create_instance(
                                    data["name"],
                                    data["memory"],
                                    data["vcpu"],
                                    data["host_model"],
                                    uuid,
                                    volumes,
                                    data["cache_mode"],
                                    data["networks"],
                                    data["virtio"],
                                    data["mac"],
                                )
                                create_instance = Instance(compute_id=compute_id, name=data["name"], uuid=uuid)
                                create_instance.save()
                                return HttpResponseRedirect(reverse("instance", args=[compute_id, data["name"]]))
                            except libvirtError as lib_err:
                                if data["hdd_size"]:
                                    conn.delete_volume(volumes.keys()[0])
                                error_messages.append(lib_err)
        conn.close()

    return render(request, "create_instance.html", locals())
Exemplo n.º 10
0
def create_instance(request, compute_id, arch, machine):
    """
    :param request:
    :param compute_id:
    :param arch:
    :param machine:
    :return:
    """
    if not request.user.is_superuser:
        return HttpResponseRedirect(reverse('index'))

    conn = None
    error_messages = list()
    storages = list()
    networks = list()
    hypervisors = list()
    firmwares = list()
    meta_prealloc = False
    compute = get_object_or_404(Compute, pk=compute_id)
    flavors = Flavor.objects.filter().order_by('id')

    try:
        conn = wvmCreate(compute.hostname, compute.login, compute.password,
                         compute.type)

        default_firmware = INSTANCE_FIRMWARE_DEFAULT_TYPE
        default_cpu_mode = INSTANCE_CPU_DEFAULT_MODE
        instances = conn.get_instances()
        videos = conn.get_video_models(arch, machine)
        cache_modes = sorted(conn.get_cache_modes().items())
        default_cache = INSTANCE_VOLUME_DEFAULT_CACHE.lower()
        default_io = INSTANCE_VOLUME_DEFAULT_IO.lower()
        default_zeroes = INSTANCE_VOLUME_DEFAULT_DETECT_ZEROES.lower()
        default_discard = INSTANCE_VOLUME_DEFAULT_DISCARD.lower()
        listener_addr = QEMU_CONSOLE_LISTEN_ADDRESSES
        mac_auto = util.randomMAC()
        disk_devices = conn.get_disk_device_types(arch, machine)
        disk_buses = conn.get_disk_bus_types(arch, machine)
        default_bus = INSTANCE_VOLUME_DEFAULT_BUS
        networks = sorted(conn.get_networks())
        nwfilters = conn.get_nwfilters()
        storages = sorted(conn.get_storages(only_actives=True))
        default_graphics = QEMU_CONSOLE_DEFAULT_TYPE

        dom_caps = conn.get_dom_capabilities(arch, machine)
        caps = conn.get_capabilities(arch)

        virtio_support = conn.is_supports_virtio(arch, machine)
        hv_supports_uefi = conn.supports_uefi_xml(dom_caps["loader_enums"])
        # Add BIOS
        label = conn.label_for_firmware_path(arch, None)
        if label: firmwares.append(label)
        # Add UEFI
        loader_path = conn.find_uefi_path_for_arch(arch, dom_caps["loaders"])
        label = conn.label_for_firmware_path(arch, loader_path)
        if label: firmwares.append(label)
        firmwares = list(set(firmwares))

    except libvirtError as lib_err:
        error_messages.append(lib_err)

    if conn:
        if not storages:
            msg = _("You haven't defined any storage pools")
            error_messages.append(msg)
        if not networks:
            msg = _("You haven't defined any network pools")
            error_messages.append(msg)

        if request.method == 'POST':
            if 'create_flavor' in request.POST:
                form = FlavorAddForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    create_flavor = Flavor(label=data['label'],
                                           vcpu=data['vcpu'],
                                           memory=data['memory'],
                                           disk=data['disk'])
                    create_flavor.save()
                    return HttpResponseRedirect(request.get_full_path())
            if 'delete_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                delete_flavor = Flavor.objects.get(id=flavor_id)
                delete_flavor.delete()
                return HttpResponseRedirect(request.get_full_path())
            if 'create' in request.POST:
                firmware = dict()
                volume_list = list()
                is_disk_created = False
                clone_path = ""
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if data['meta_prealloc']:
                        meta_prealloc = True
                    if instances:
                        if data['name'] in instances:
                            msg = _(
                                "A virtual machine with this name already exists"
                            )
                            error_messages.append(msg)
                        if Instance.objects.filter(name__exact=data['name']):
                            messages.warning(
                                request,
                                _("There is an instance with same name. Are you sure?"
                                  ))
                    if not error_messages:
                        if data['hdd_size']:
                            if not data['mac']:
                                error_msg = _(
                                    "No Virtual Machine MAC has been entered")
                                error_messages.append(error_msg)
                            else:
                                try:
                                    path = conn.create_volume(
                                        data['storage'],
                                        data['name'],
                                        data['hdd_size'],
                                        metadata=meta_prealloc)
                                    volume = dict()
                                    volume['path'] = path
                                    volume['type'] = conn.get_volume_type(path)
                                    volume['device'] = 'disk'
                                    if data['virtio']:
                                        volume[
                                            'bus'] = INSTANCE_VOLUME_DEFAULT_BUS
                                    volume_list.append(volume)
                                    is_disk_created = True
                                except libvirtError as lib_err:
                                    error_messages.append(lib_err)
                        elif data['template']:
                            templ_path = conn.get_volume_path(data['template'])
                            dest_vol = conn.get_volume_path(
                                data["name"] + ".img", data['storage'])
                            if dest_vol:
                                error_msg = _(
                                    "Image has already exist. Please check volumes or change instance name"
                                )
                                error_messages.append(error_msg)
                            else:
                                clone_path = conn.clone_from_template(
                                    data['name'],
                                    templ_path,
                                    data['storage'],
                                    metadata=meta_prealloc)
                                volume = dict()
                                volume['path'] = clone_path
                                volume['type'] = conn.get_volume_type(
                                    clone_path)
                                volume['device'] = 'disk'
                                if data['virtio']:
                                    volume['bus'] = INSTANCE_VOLUME_DEFAULT_BUS
                                volume_list.append(volume)
                                is_disk_created = True
                        else:
                            if not data['images']:
                                error_msg = _(
                                    "First you need to create or select an image"
                                )
                                error_messages.append(error_msg)
                            else:
                                for idx, vol in enumerate(
                                        data['images'].split(',')):
                                    try:
                                        path = conn.get_volume_path(vol)
                                        volume = dict()
                                        volume['path'] = path
                                        volume['type'] = conn.get_volume_type(
                                            path)
                                        volume['device'] = request.POST.get(
                                            'device' + str(idx), '')
                                        volume['bus'] = request.POST.get(
                                            'bus' + str(idx), '')
                                        volume_list.append(volume)
                                    except libvirtError as lib_err:
                                        error_messages.append(lib_err)
                        if data['cache_mode'] not in conn.get_cache_modes():
                            error_msg = _("Invalid cache mode")
                            error_messages.append(error_msg)

                        if 'UEFI' in data["firmware"]:
                            firmware["loader"] = data["firmware"].split(
                                ":")[1].strip()
                            firmware["secure"] = 'no'
                            firmware["readonly"] = 'yes'
                            firmware["type"] = 'pflash'
                            if 'secboot' in firmware[
                                    "loader"] and machine != 'q35':
                                messages.warning(
                                    request,
                                    "Changing machine type from '%s' to 'q35' "
                                    "which is required for UEFI secure boot." %
                                    machine)
                                machine = 'q35'
                                firmware["secure"] = 'yes'

                        if not error_messages:
                            uuid = util.randomUUID()
                            try:
                                conn.create_instance(
                                    name=data['name'],
                                    memory=data['memory'],
                                    vcpu=data['vcpu'],
                                    vcpu_mode=data['vcpu_mode'],
                                    uuid=uuid,
                                    arch=arch,
                                    machine=machine,
                                    firmware=firmware,
                                    images=volume_list,
                                    cache_mode=data['cache_mode'],
                                    io_mode=default_io,
                                    discard_mode=default_discard,
                                    detect_zeroes_mode=default_zeroes,
                                    networks=data['networks'],
                                    virtio=data['virtio'],
                                    listen_addr=data["listener_addr"],
                                    nwfilter=data["nwfilter"],
                                    graphics=data["graphics"],
                                    video=data["video"],
                                    console_pass=data["console_pass"],
                                    mac=data['mac'],
                                    qemu_ga=data['qemu_ga'])
                                create_instance = Instance(
                                    compute_id=compute_id,
                                    name=data['name'],
                                    uuid=uuid)
                                create_instance.save()
                                msg = _("Instance is created.")
                                messages.success(request, msg)
                                addlogmsg(request.user.username,
                                          create_instance.name, msg)
                                return HttpResponseRedirect(
                                    reverse('instance',
                                            args=[compute_id, data['name']]))
                            except libvirtError as lib_err:
                                if data['hdd_size'] or len(volume_list) > 0:
                                    if is_disk_created:
                                        for vol in volume_list:
                                            conn.delete_volume(vol['path'])
                                error_messages.append(lib_err)
        conn.close()
    return render(request, 'create_instance_w2.html', locals())
Exemplo n.º 11
0
def create_instance(request, compute_id):
    """
    :param request:
    :return:
    """

    if not request.user.is_superuser:
        return HttpResponseRedirect(reverse('index'))

    conn = None
    error_messages = []
    storages = []
    networks = []
    meta_prealloc = False
    compute = get_object_or_404(Compute, pk=compute_id)
    flavors = Flavor.objects.filter().order_by('id')

    try:
        conn = wvmCreate(compute.hostname,
                         compute.login,
                         compute.password,
                         compute.type)

        storages = sorted(conn.get_storages(only_actives=True))
        networks = sorted(conn.get_networks())
        nwfilters = conn.get_nwfilters()
        instances = conn.get_instances()
        videos = conn.get_video()
        cache_modes = sorted(conn.get_cache_modes().items())
        default_cache = INSTANCE_VOLUME_DEFAULT_CACHE
        listener_addr = QEMU_CONSOLE_LISTEN_ADDRESSES
        mac_auto = util.randomMAC()
        disk_devices = conn.get_disk_device_types()
        disk_buses = conn.get_disk_bus_types()
        default_bus = INSTANCE_VOLUME_DEFAULT_BUS
    except libvirtError as lib_err:
        error_messages.append(lib_err)

    if conn:
        if not storages:
            msg = _("You haven't defined any storage pools")
            error_messages.append(msg)
        if not networks:
            msg = _("You haven't defined any network pools")
            error_messages.append(msg)

        if request.method == 'POST':
            if 'create_flavor' in request.POST:
                form = FlavorAddForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    create_flavor = Flavor(label=data['label'],
                                           vcpu=data['vcpu'],
                                           memory=data['memory'],
                                           disk=data['disk'])
                    create_flavor.save()
                    return HttpResponseRedirect(request.get_full_path())
            if 'delete_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                delete_flavor = Flavor.objects.get(id=flavor_id)
                delete_flavor.delete()
                return HttpResponseRedirect(request.get_full_path())
            if 'create_xml' in request.POST:
                xml = request.POST.get('dom_xml', '')
                try:
                    name = util.get_xml_path(xml, '/domain/name')
                except util.etree.Error as err:
                    name = None
                if name in instances:
                    error_msg = _("A virtual machine with this name already exists")
                    error_messages.append(error_msg)
                else:
                    try:
                        conn._defineXML(xml)
                        return HttpResponseRedirect(reverse('instance', args=[compute_id, name]))
                    except libvirtError as lib_err:
                        error_messages.append(lib_err.message)
            if 'create' in request.POST:
                volume_list = []

                clone_path = ""
                form = NewVMForm(request.POST)
                if form.is_valid():
                    data = form.cleaned_data
                    if data['meta_prealloc']:
                        meta_prealloc = True
                    if instances:
                        if data['name'] in instances:
                            msg = _("A virtual machine with this name already exists")
                            error_messages.append(msg)
                        if Instance.objects.filter(name__exact=data['name']):
                            messages.warning(request,_("There is an instance with same name. Are you sure?"))
                    if not error_messages:
                        if data['hdd_size']:
                            if not data['mac']:
                                error_msg = _("No Virtual Machine MAC has been entered")
                                error_messages.append(error_msg)
                            else:
                                try:
                                    path = conn.create_volume(data['storage'], data['name'], data['hdd_size'],
                                                              metadata=meta_prealloc)
                                    volume = dict()
                                    volume['path'] = path
                                    volume['type'] = conn.get_volume_type(path)
                                    volume['device'] = 'disk'
                                    volume['bus'] = 'virtio'
                                    volume_list.append(volume)
                                except libvirtError as lib_err:
                                    error_messages.append(lib_err.message)
                        elif data['template']:
                            templ_path = conn.get_volume_path(data['template'])
                            dest_vol = conn.get_volume_path(data["name"] + ".img", data['storage'])
                            if dest_vol:
                                error_msg = _("Image has already exist. Please check volumes or change instance name")
                                error_messages.append(error_msg)
                            else:
                                clone_path = conn.clone_from_template(data['name'], templ_path, data['storage'], metadata=meta_prealloc)
                                volume = dict()
                                volume['path'] = clone_path
                                volume['type'] = conn.get_volume_type(clone_path)
                                volume['device'] = 'disk'
                                volume['bus'] = 'virtio'
                                volume_list.append(volume)
                        else:
                            if not data['images']:
                                error_msg = _("First you need to create or select an image")
                                error_messages.append(error_msg)
                            else:
                                for idx, vol in enumerate(data['images'].split(',')):
                                    try:

                                        path = conn.get_volume_path(vol)
                                        volume = dict()
                                        volume['path'] = path
                                        volume['type'] = conn.get_volume_type(path)
                                        volume['device'] = request.POST.get('device' + str(idx), '')
                                        volume['bus'] = request.POST.get('bus' + str(idx), '')
                                        volume_list.append(volume)
                                    except libvirtError as lib_err:
                                        error_messages.append(lib_err.message)
                        if data['cache_mode'] not in conn.get_cache_modes():
                            error_msg = _("Invalid cache mode")
                            error_messages.append(error_msg)
                        if not error_messages:
                            uuid = util.randomUUID()
                            try:
                                conn.create_instance(data['name'], data['memory'], data['vcpu'], data['host_model'],
                                                     uuid, volume_list, data['cache_mode'], data['networks'], data['virtio'],
                                                     data["listener_addr"], data["nwfilter"], data["video"], data["console_pass"],
                                                     data['mac'], data['qemu_ga'])
                                create_instance = Instance(compute_id=compute_id, name=data['name'], uuid=uuid)
                                create_instance.save()
                                msg = _("Instance is created.")
                                messages.success(request, msg)
                                addlogmsg(request.user.username, create_instance.name, msg)
                                return HttpResponseRedirect(reverse('instance', args=[compute_id, data['name']]))
                            except libvirtError as lib_err:
                                if data['hdd_size'] or volume_list.count() > 0:
                                    for vol in volume_list:
                                        conn.delete_volume(vol['path'])
                                error_messages.append(lib_err)
        conn.close()
    return render(request, 'create_instance.html', locals())