def create_network(self, name, forward, gateway, mask, dhcp, bridge, openvswitch, fixed=False): xml = """ <network> <name>%s</name>""" % name if forward in ['nat', 'route', 'bridge']: xml += """<forward mode='%s'/>""" % forward xml += """<bridge """ if forward in ['nat', 'route', 'none']: xml += """stp='on' delay='0'""" if forward == 'bridge': xml += """name='%s'""" % bridge xml += """/>""" if openvswitch is True: xml += """<virtualport type='openvswitch'/>""" if forward != 'bridge': xml += """ <ip address='%s' netmask='%s'>""" % (gateway, mask) if dhcp: xml += """<dhcp> <range start='%s' end='%s' />""" % (dhcp[0], dhcp[1]) if fixed: fist_oct = int(dhcp[0].strip().split('.')[3]) last_oct = int(dhcp[1].strip().split('.')[3]) for ip in range(fist_oct, last_oct + 1): xml += """<host mac='%s' ip='%s.%s' />""" % (util.randomMAC(), gateway[:-2], ip) xml += """</dhcp>""" xml += """</ip>""" xml += """</network>""" self.define_network(xml) net = self.get_network(name) net.create() net.setAutostart(1)
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))
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))
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())
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))
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())
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())
def create_instance(self, name, memory, vcpu, uuid, images, networks, host_model=False, virtio=True, template_ver3=True): """ Create VM function """ memory = int(memory) * 1024 if self.is_kvm_supported(): hypervisor_type = 'kvm' else: hypervisor_type = 'qemu' vm_template = "ver4" if template_ver3: vm_template = "ver3" xml = u""" <domain type='%s'> <name>%s</name> <description>%s</description> <uuid>%s</uuid> <memory unit='KiB'>%s</memory> <vcpu>%s</vcpu>""" % (hypervisor_type, name, vm_template, uuid, memory, vcpu) if host_model: xml += """<cpu mode='host-model'/>""" xml +=u"""<os> <type arch='%s'>%s</type> <boot dev='hd'/> <boot dev='cdrom'/> <bootmenu enable='yes'/> </os>""" % (self.get_host_arch(), self.get_os_type()) xml += u"""<features> <acpi/><apic/><pae/> </features> <clock offset="utc"/> <on_poweroff>destroy</on_poweroff> <on_reboot>restart</on_reboot> <on_crash>restart</on_crash> <devices>""" disk_letters = list(string.lowercase) for image, img_type in images.items(): stg = self.get_storage_by_vol_path(image) stg_type = util.get_xml_path(stg.XMLDesc(0), "/pool/@type") if stg_type == 'rbd': ceph_user, secrt_uuid, ceph_host = get_rbd_storage_data(stg) xml += u"""<disk type='network' device='disk'> <driver name='qemu' type='%s'/> <auth username='******'> <secret type='ceph' uuid='%s'/> </auth> <source protocol='rbd' name='%s'> <host name='%s' port='6789'/> </source>""" % (img_type, ceph_user, secrt_uuid, image, ceph_host) else: xml += u"""<disk type='file' device='disk'> <driver name='qemu' type='%s'/> <source file='%s'/>""" % (img_type, image) if virtio: xml += u"""<target dev='vd%s' bus='virtio'/>""" % (disk_letters.pop(0),) else: xml += u"""<target dev='sd%s' bus='ide'/>""" % (disk_letters.pop(0),) xml += u"""</disk>""" xml += u""" <disk type='file' device='cdrom'> <driver name='qemu' type='raw'/> <source file=''/> <target dev='hda' bus='ide'/> <readonly/> <address type='drive' controller='0' bus='1' target='0' unit='1'/> </disk>""" xml += u""" <interface type='bridge'> <mac address='%s'/> <source bridge='br0'/> <model type='e1000'/> <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/> </interface>""" % util.randomMAC() hd_resources = util.load_hd_resources() slot_index = 6 for net in networks: slot_index = slot_index + 1 xml += u"""<hostdev mode='subsystem' type='pci' managed='yes'><source>""" bus = net.split(":")[0] slot = net.split(":")[1].split(".")[0] func = net.split(":")[1].split(".")[1] hd_resources[net]['used'] = 1 xml += u"""<address domain='0x0000' bus='0x%s' slot='0x%s' function='0x%s'/></source>""" % (bus, slot, func) xml += u"""<address type='pci' domain='0x0000' bus='0x00' slot='0x%02x' function='0x0'/>""" % slot_index xml += u"""</hostdev>""" hd_resources["mem"] = int(hd_resources["mem"]) - memory / (1024*1024) hd_resources["vcpu"] = int(hd_resources["vcpu"]) - vcpu util.save_hd_resources(hd_resources) xml += u""" <input type='mouse' bus='ps2'/> <input type='tablet' bus='usb'/> <graphics type='%s' port='-1' autoport='yes' listen='0.0.0.0'> <listen type='address' address='0.0.0.0'/> </graphics> <console type='pty'/> <video> <model type='cirrus'/> </video> <memballoon model='virtio'/> </devices> </domain>""" % QEMU_CONSOLE_DEFAULT_TYPE self._defineXML(xml)
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())