def delete_instance(instance, delete_disk=False): compute = instance.compute instance_name = instance.name try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, instance.name) del_userinstance = UserInstance.objects.filter(instance=instance) if del_userinstance: print("Deleting UserInstances") print(del_userinstance) del_userinstance.delete() if conn.get_status() == 1: print("Forcing shutdown") conn.force_shutdown() if delete_disk: snapshots = sorted(conn.get_snapshot(), reverse=True, key=lambda k:k['date']) for snap in snapshots: print("Deleting snapshot {}".format(snap['name'])) conn.snapshot_delete(snap['name']) print("Deleting disks") conn.delete_disk() conn.delete() instance.delete() print("Instance {} on compute {} sucessfully deleted".format(instance_name, compute.hostname)) except libvirtError as lib_err: print("Error removing instance {} on compute {}".format(instance_name, compute.hostname)) raise lib_err
def do_execute(self, quick_model: create_models.QuickVM): if not quick_model.instance: return None if not quick_model.compute_id or not compute_models.Compute.objects.filter( id=quick_model.compute_id).exists(): return None instance = quick_model.instance compute = compute_models.Compute.objects.get(id=quick_model.compute_id) # 做一些清理工作 conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, quick_model.instance.name) status = conn.get_status() # 状态为 5 ,表示关闭,可以删除 if status != 5: raise Exception('%s is not shutdwon in host %s' % (quick_model.instance.name, compute.name)) snapshots = sorted(conn.get_snapshot(), reverse=True, key=lambda k: k['date']) for snap in snapshots: conn.snapshot_delete(snap['name']) conn.delete_disk() conn.delete() conn.close() instance.delete() quick_model.refresh_from_db()
def inst_status(request, compute_id, vname): """ :param request: :return: """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) compute = get_object_or_404(Compute, pk=compute_id) response = HttpResponse() response['Content-Type'] = "text/javascript" try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) data = json.dumps({'status': conn.get_status()}) conn.close() except libvirtError: data = json.dumps({'error': 'Error 500'}) response.write(data) return response
def console(request): """ VNC instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') if request.method == 'GET': uuid = request.GET.get('token', '') try: instance = Instance.objects.get(uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) vnc_passwd = conn.get_vnc_passwd() except: vnc_passwd = None wsproxy_port = WS_PORT wsproxy_host = request.get_host() if ':' in wsproxy_host: wsproxy_host = re.sub(':[0-9]+', '', wsproxy_host) response = render_to_response('console.html', locals(), context_instance=RequestContext(request)) response.set_cookie('token', uuid) return response
def inst_status(request, host_id, vname): """ Instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() conn.close() except libvirtError: status = None data = json.dumps({'status': status}) response = HttpResponse() response['Content-Type'] = "text/javascript" response.write(data) return response
def powerGroupInstance(request, group_id): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) if not request.user.is_superuser: return HttpResponseRedirect(reverse('index')) group = get_object_or_404(Group, pk=group_id) msg = ("Power On Group") try: group_instances = Instance.objects.filter(group=group).order_by('name') except: pass group_instances_status = [] # get status for each instances of the group for instance in group_instances: conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) if conn.get_status() != 1: conn.start() return redirect('group', group_id=group_id)
def cpuusage(request, host_id, vname): """ VM cpu usage """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') datasets = [] compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) cpu_usage = conn.cpu_usage() conn.close() except libvirtError: cpu_usage = 0 try: cookies = request._cookies['cpu_usage'] except KeyError: cookies = None if not cookies: datasets.append(0) else: datasets = eval(cookies) if len(datasets) > 10: while datasets: del datasets[0] if len(datasets) == 10: break if len(datasets) <= 9: datasets.append(int(cpu_usage['cpu'])) if len(datasets) == 10: datasets.append(int(cpu_usage['cpu'])) del datasets[0] cpu = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(241,72,70,0.5)", "strokeColor": "rgba(241,72,70,1)", "pointColor": "rgba(241,72,70,1)", "pointStrokeColor": "#fff", "data": datasets } ] } data = simplejson.dumps(cpu) response = HttpResponse() response['Content-Type'] = "text/javascript" response.cookies['cpu_usage'] = datasets response.write(data) return response
def console(request): """ VNC instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') if request.method == 'GET': token = request.GET.get('token', '') try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) vnc_websocket_port = conn.get_vnc_websocket_port() vnc_passwd = conn.get_vnc_passwd() except: vnc_websocket_port = None vnc_passwd = None ws_port = vnc_websocket_port if vnc_websocket_port else WS_PORT ws_host = request.get_host() if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) response = render_to_response('console.html', locals(), context_instance=RequestContext(request)) response.set_cookie('token', token) return response
def console(request): """ VNC instance block """ if request.method == "GET": token = request.GET.get("token", "") try: temptoken = token.split("-", 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance( instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name, ) vnc_websocket_port = conn.get_vnc_websocket_port() vnc_passwd = conn.get_vnc_passwd() except: vnc_websocket_port = None vnc_passwd = None ws_port = vnc_websocket_port if vnc_websocket_port else WS_PORT ws_host = request.get_host() if ":" in ws_host: ws_host = re.sub(":[0-9]+", "", ws_host) response = render(None, "console.html", locals(), request) response.set_cookie("token", token) return response
def check_user_quota(instance, cpu, memory, disk_size): user_instances = UserInstance.objects.filter(user_id=request.user.id, instance__is_template=False) instance += len(user_instances) for usr_inst in user_instances: if connection_manager.host_is_up(usr_inst.instance.compute.type, usr_inst.instance.compute.hostname): conn = wvmInstance(usr_inst.instance.compute, usr_inst.instance.compute.login, usr_inst.instance.compute.password, usr_inst.instance.compute.type, usr_inst.instance.name) cpu += int(conn.get_vcpu()) memory += int(conn.get_memory()) for disk in conn.get_disk_device(): disk_size += int(disk['size'])>>30 ua = request.user.userattributes msg = "" if ua.max_instances > 0 and instance > ua.max_instances: msg = "instance" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (instance, ua.max_instances) if ua.max_cpus > 0 and cpu > ua.max_cpus: msg = "cpu" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (cpu, ua.max_cpus) if ua.max_memory > 0 and memory > ua.max_memory: msg = "memory" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (memory, ua.max_memory) if ua.max_disk_size > 0 and disk_size > ua.max_disk_size: msg = "disk" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (disk_size, ua.max_disk_size) return msg
def delete_instance(instance, delete_disk=False): compute = instance.compute instance_name = instance.name try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, instance.name) del_userinstance = UserInstance.objects.filter(instance=instance) if del_userinstance: print("Deleting UserInstances") print(del_userinstance) del_userinstance.delete() if conn.get_status() == 1: print("Forcing shutdown") conn.force_shutdown() if delete_disk: snapshots = sorted(conn.get_snapshot(), reverse=True) for snap in snapshots: print("Deleting snapshot {}".format(snap['name'])) conn.snapshot_delete(snap['name']) print("Deleting disks") conn.delete_disk() conn.delete() instance.delete() print("Instance {} on compute {} sucessfully deleted".format( instance_name, compute.hostname)) except libvirtError as lib_err: print("Error removing instance {} on compute {}".format( instance_name, compute.hostname)) raise lib_err
def console(request): """ VNC instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') if request.method == 'GET': token = request.GET.get('token', '') try: host = int(token[0]) uuid = token[2:] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) vnc_passwd = conn.get_vnc_passwd() except: vnc_passwd = None wsproxy_port = WS_PORT wsproxy_host = request.get_host() if ':' in wsproxy_host: wsproxy_host = re.sub(':[0-9]+', '', wsproxy_host) response = render_to_response('console.html', locals(), context_instance=RequestContext(request)) response.set_cookie('token', token) return response
def console(request): """ VNC instance block """ if request.method == 'GET': token = request.GET.get('token', '') try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) vnc_websocket_port = conn.get_vnc_websocket_port() vnc_passwd = conn.get_vnc_passwd() except: vnc_websocket_port = None vnc_passwd = None ws_port = vnc_websocket_port if vnc_websocket_port else WS_PORT ws_host = request.get_host() if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) response = render(None, 'console.html', locals(), request) response.set_cookie('token', token) return response
def console(request): """ VNC instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect("/login") if request.method == "GET": token = request.GET.get("token", "") try: temptoken = token.split("-", 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance( instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name, ) vnc_passwd = conn.get_vnc_passwd() except: vnc_passwd = None wsproxy_port = WS_PORT wsproxy_host = request.get_host() if ":" in wsproxy_host: wsproxy_host = re.sub(":[0-9]+", "", wsproxy_host) response = render_to_response("console.html", locals(), context_instance=RequestContext(request)) response.set_cookie("token", token) return response
def proxy(self): return wvmInstance( self.compute.hostname, self.compute.login, self.compute.password, self.compute.type, self.name, )
def migrate_instance( new_compute, instance, user, live=False, unsafe=False, xml_del=False, offline=False, autoconverge=False, compress=False, postcopy=False, ): status = connection_manager.host_is_up(new_compute.type, new_compute.hostname) if not status: return if new_compute == instance.compute: return try: conn_migrate = wvmInstances( new_compute.hostname, new_compute.login, new_compute.password, new_compute.type, ) autostart = instance.autostart conn_migrate.moveto( instance.proxy, instance.name, live, unsafe, xml_del, offline, autoconverge, compress, postcopy, ) finally: conn_migrate.close() try: conn_new = wvmInstance( new_compute.hostname, new_compute.login, new_compute.password, new_compute.type, instance.name, ) if autostart: conn_new.set_autostart(1) finally: conn_new.close() instance.compute = new_compute instance.save()
def console(request): """ :param request: :return: """ console_error = None if request.method == "GET": token = request.GET.get("token", "") view_type = request.GET.get("view", "lite") view_only = request.GET.get("view_only", app_settings.CONSOLE_VIEW_ONLY.lower()) scale = request.GET.get("scale", app_settings.CONSOLE_SCALE.lower()) resize_session = request.GET.get( "resize_session", app_settings.CONSOLE_RESIZE_SESSION.lower()) clip_viewport = request.GET.get( "clip_viewport", app_settings.CONSOLE_CLIP_VIEWPORT.lower()) try: temptoken = token.split("-", 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance( instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name, ) console_type = conn.get_console_type() console_websocket_port = conn.get_console_websocket_port() console_passwd = conn.get_console_passwd() except libvirtError: console_type = None console_websocket_port = None console_passwd = None ws_port = console_websocket_port if console_websocket_port else WS_PUBLIC_PORT ws_host = WS_PUBLIC_HOST if WS_PUBLIC_HOST else request.get_host() ws_path = WS_PUBLIC_PATH if WS_PUBLIC_PATH else "/" if ":" in ws_host: ws_host = re.sub(":[0-9]+", "", ws_host) if console_type == "vnc" or console_type == "spice": console_page = "console-" + console_type + "-" + view_type + ".html" response = render(request, console_page, locals()) else: if console_type is None: console_error = "Fail to get console. Please check the console configuration of your VM." else: console_error = f"Console type: {console_type} no support" response = render(request, "console-vnc-lite.html", locals()) response.set_cookie("token", token) return response
def do_execute(self, quick_model: create_models.QuickVM): compute = compute_models.Compute.objects.get(id=quick_model.compute_id) conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, quick_model.instance.name) conn.start() instance = quick_model.instance instance.start_time = timezone.now() instance.save() return True
def query_machine(hostname): try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, hostname) object[hostname] = { 'status': conn.get_status(), 'cur_memory': conn.get_cur_memory(), 'disks': conn.get_disk_device(), 'vcpu': conn.get_vcpu() } except libvirtError: status = None
def console(request): """ Console instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) if request.method == 'GET': token = request.GET.get('token', '') temptoken = token.split('-', 1) host_id = int(temptoken[0]) uuid = temptoken[1] compute = Compute.objects.get(id=host_id) vm = Instance.objects.get(uuid=uuid) try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name, instance.compute.hypervisor) console_type = conn.get_console_type() console_websocket_port = conn.get_console_websocket_port() console_passwd = conn.get_console_passwd() except: console_type = None console_websocket_port = None console_passwd = None ws_port = console_websocket_port if console_websocket_port else WS_PORT ws_host = WS_PUBLIC_HOST if WS_PUBLIC_HOST else request.get_host() if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) if console_type == 'vnc': response = render_to_response('console-vnc.html', locals(), context_instance=RequestContext(request)) elif console_type == 'spice': response = render_to_response('console-spice.html', locals(), context_instance=RequestContext(request)) else: response = "Console type %s no support" % console_type response.set_cookie('token', token) return response
def console(request): """ :param request: :return: """ console_error = None if request.method == 'GET': token = request.GET.get('token', '') view_type = request.GET.get('view', 'lite') view_only = request.GET.get('view_only', 0) scale = request.GET.get('scale', 0) resize_session = request.GET.get('resize_session', 0) clip_viewport = request.GET.get('clip_viewport', 0) try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) console_type = conn.get_console_type() console_websocket_port = conn.get_console_websocket_port() console_passwd = conn.get_console_passwd() except libvirtError: console_type = None console_websocket_port = None console_passwd = None ws_port = console_websocket_port if console_websocket_port else WS_PUBLIC_PORT ws_host = WS_PUBLIC_HOST if WS_PUBLIC_HOST else request.get_host() ws_path = WS_PUBLIC_PATH if WS_PUBLIC_PATH else '/' if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) console_page = "console-" + console_type + "-" + view_type + ".html" if console_type == 'vnc' or console_type == 'spice': response = render(request, console_page, locals()) else: console_error = f"Console type: {console_type} no support" response = render(request, 'console-vnc-lite.html', locals()) response.set_cookie('token', token) return response
def inst_status(request, host_id, vname): if not request.user.is_authenticated(): return redirect('login') compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() conn.close() except libvirtError: status = None data = json.dumps({'status': status}) return HttpResponse(data, 'text/javascript')
def check_user_quota(user, instance, cpu, memory, disk_size): ua = user.userattributes msg = "" if user.is_superuser: return msg quota_debug = app_settings.QUOTA_DEBUG user_instances = UserInstance.objects.filter(user=user, instance__is_template=False) instance += user_instances.count() for usr_inst in user_instances: if connection_manager.host_is_up( usr_inst.instance.compute.type, usr_inst.instance.compute.hostname, ): conn = wvmInstance( usr_inst.instance.compute.hostname, usr_inst.instance.compute.login, usr_inst.instance.compute.password, usr_inst.instance.compute.type, usr_inst.instance.name, ) cpu += int(conn.get_vcpu()) memory += int(conn.get_memory()) for disk in conn.get_disk_devices(): if disk['size']: disk_size += int(disk['size']) >> 30 if ua.max_instances > 0 and instance > ua.max_instances: msg = "instance" if quota_debug: msg += f" ({instance} > {ua.max_instances})" if ua.max_cpus > 0 and cpu > ua.max_cpus: msg = "cpu" if quota_debug: msg += f" ({cpu} > {ua.max_cpus})" if ua.max_memory > 0 and memory > ua.max_memory: msg = "memory" if quota_debug: msg += f" ({memory} > {ua.max_memory})" if ua.max_disk_size > 0 and disk_size > ua.max_disk_size: msg = "disk" if quota_debug: msg += f" ({disk_size} > {ua.max_disk_size})" return msg
def snap_crontab(): computes = computes_models.Compute.objects.all() for compute in computes: # 忽略不可连接的宿主 if connection_manager.host_is_up(compute.type, compute.hostname) is not True: continue conn = wvmHostDetails(compute.hostname, compute.login, compute.password, compute.type) instances = conn.get_instances() # ['name1', 'name2'] conn.close() for vname in instances: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) if conn.get_status() != 1: print("%s status is %s, skip" % (vname, conn.get_status())) continue snapshot_list = conn.instance.snapshotListNames(0) snap_coll = [] # [{'created': <int>, 'snap':snap_obj}, ...] # 收集快照信息 for snapshot_name in snapshot_list: snap = conn.instance.snapshotLookupByName(snapshot_name, 0) snap_time_create = util.get_xml_path( snap.getXMLDesc(0), "/domainsnapshot/creationTime") snap_coll.append({ 'created': int(snap_time_create), 'snap': snap }) # 若快照数量高于7个,删除旧的快照 if len(snap_coll) >= 6: snap_coll = sorted(snap_coll, reverse=True, key=lambda d: d['created']) for item in snap_coll[6:]: snap = item['snap'] snap.delete(0) # 创建一个新的快照 snap_name = datetime.datetime.now().strftime('%m-%d %H:%M:%S') conn.create_snapshot(snap_name) conn.close() print("end snap_crontab")
def console(request): """ Console instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) if request.method == 'GET': token = request.GET.get('token', '') try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) name = instance.name console_type = conn.get_console_type() console_websocket_port = conn.get_console_websocket_port() console_passwd = conn.get_console_passwd() except: console_type = None console_websocket_port = None console_passwd = None ws_port = console_websocket_port if console_websocket_port else WS_PORT ws_host = WS_PUBLIC_HOST if WS_PUBLIC_HOST else request.get_host() if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) if console_type == 'vnc': response = render_to_response('console-vnc.html', locals(), context_instance=RequestContext(request)) elif console_type == 'spice': response = render_to_response('console-spice.html', locals(), context_instance=RequestContext(request)) else: response = "Console type %s no support" % console_type response.set_cookie('token', token) return response
def get_vdi_url(request, vname): instance = Instance.objects.get(name=vname) compute = instance.compute data = {} try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, instance.name) fqdn = get_hostname_by_ip(compute.hostname) url = "{}://{}:{}".format(conn.get_console_type(), fqdn, conn.get_console_port()) response = url return HttpResponse(response) except libvirtError as lib_err: err = "Error getting vdi url for {}".format(vname) raise Http404(err)
def console(request): """ :param request: :return: """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) if request.method == 'GET': token = request.GET.get('token', '') try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) console_type = conn.get_console_type() console_websocket_port = conn.get_console_websocket_port() console_passwd = conn.get_console_passwd() except libvirtError as lib_err: console_type = None console_websocket_port = None console_passwd = None ws_port = console_websocket_port if console_websocket_port else WS_PUBLIC_PORT ws_host = WS_PUBLIC_HOST if WS_PUBLIC_HOST else request.get_host() ws_path = WS_PUBLIC_PATH if WS_PUBLIC_PATH else '/' if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) if console_type == 'vnc': response = render(request, 'console-vnc.html', locals()) elif console_type == 'spice': response = render(request, 'console-spice.html', locals()) else: response = "Console type %s no support" % console_type response.set_cookie('token', token) return response
def inst_status(request, compute_id, vname): """ :param request: :return: """ compute = get_object_or_404(Compute, pk=compute_id) response = HttpResponse() response["Content-Type"] = "text/javascript" try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) data = json.dumps({"status": conn.get_status()}) conn.close() except libvirtError: data = json.dumps({"error": "Error 500"}) response.write(data) return response
def query_machine(hostname): try: conn2 = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, hostname) results[hostname] = ({'name': hostname, #'status': conn.get_instance_status(instance), #'uuid': uuid, #'memory': conn.get_instance_memory(instance), 'description': conn2.get_description(), #'vcpu': conn.get_instance_vcpu(instance), #'storage': conn2.get_disk_device(), #'has_managed_save_image': conn.get_instance_managed_save_image(instance) }) conn2.close() except libvirtError: status = None
def editGroup(request, group_id): """ :param request: :return: """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) if not request.user.is_superuser: return HttpResponseRedirect(reverse('index')) error_messages = [] if request.method == 'POST': form = groupInstanceAddForm(request.POST) if form.is_valid(): groupInstance = form.cleaned_data group = get_object_or_404(Group, pk=group_id) instance = get_object_or_404(Instance, pk=groupInstance['instance_id']) instance.group = group instance.save() return HttpResponseRedirect(request.get_full_path()) else: for msg_err in form.errors.values(): error_messages.append(msg_err.as_text()) group = get_object_or_404(Group, pk=group_id) available_instances = Instance.objects.filter(group=None).order_by('name') group_instances = [] try: group_instances = Instance.objects.filter(group=group).order_by('name') except: pass group_instances_status = [] # get status for each instances of the group for instance in group_instances: conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) status = conn.get_status() group_instances_status.append((instance,status)) return render(request, 'group.html', locals())
def console(request): """ :param request: :return: """ if request.method == 'GET': token = request.GET.get('token', '') try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) console_type = conn.get_console_type() console_websocket_port = conn.get_console_websocket_port() console_passwd = conn.get_console_passwd() except libvirtError as lib_err: console_type = None console_websocket_port = None console_passwd = None ws_port = console_websocket_port if console_websocket_port else WS_PORT ws_host = WS_PUBLIC_HOST if WS_PUBLIC_HOST else request.get_host() ws_path = WS_PATH if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) if console_type == 'vnc': response = render(request, 'console-vnc.html', locals()) elif console_type == 'spice': response = render(request, 'console-spice.html', locals()) else: response = "Console type %s no support" % console_type response.set_cookie('token', token) return response
def editGroup(request, group_id): """ :param request: :return: """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) if not request.user.is_superuser: return HttpResponseRedirect(reverse('index')) error_messages = [] if request.method == 'POST': form = groupInstanceAddForm(request.POST) if form.is_valid(): groupInstance = form.cleaned_data group = get_object_or_404(Group, pk=group_id) instance = get_object_or_404(Instance, pk=groupInstance['instance_id']) instance.group = group instance.save() return HttpResponseRedirect(request.get_full_path()) else: for msg_err in form.errors.values(): error_messages.append(msg_err.as_text()) group = get_object_or_404(Group, pk=group_id) available_instances = Instance.objects.filter(group=None).order_by('name') group_instances = [] try: group_instances = Instance.objects.filter(group=group).order_by('name') except: pass group_instances_status = [] # get status for each instances of the group for instance in group_instances: conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) status = conn.get_status() group_instances_status.append((instance, status)) return render(request, 'group.html', locals())
def get_vdi_url(request, compute_id, vname): """ :param request: :param vname: :return: """ compute = get_object_or_404(Compute, pk=compute_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) fqdn = get_hostname_by_ip(compute.hostname) url = f"{conn.get_console_type()}://{fqdn}:{conn.get_console_port()}" response = url return HttpResponse(response) except libvirtError: err = "Error getting VDI URL for %(name)s" % {"name": vname} raise Http404(err)
def console(request): """ VNC instance block """ if request.method == 'GET': reqtoken = request.GET.get("token") reqstr = base64.decodestring(reqtoken) temptoken = reqstr.split('|', 2) hostname = temptoken[0] name = temptoken[1] display = temptoken[2] password = None login = None htype = 1 try: conn = wvmInstance(hostname, login, password, htype, name) vnc_websocket_port = conn.get_vnc_websocket_port() vnc_passwd = conn.get_vnc_passwd() except: vnc_websocket_port = None vnc_passwd = None ws_port = vnc_websocket_port if vnc_websocket_port else WS_PORT ws_host = request.get_host() if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) response = render_to_response('console.html', locals(), context_instance=RequestContext(request)) token = hostname + "|"+name +"|"+display des = DES() des.input_key(WS_DESKEY) encryptval = des.encode(token) response.set_cookie('token', encryptval) return response
def console(request): """ VNC instance block """ if request.method == 'GET': reqtoken = request.GET.get("token") reqstr = base64.decodestring(reqtoken) temptoken = reqstr.split('|', 2) hostname = temptoken[0] name = temptoken[1] display = temptoken[2] password = None login = None htype = 1 try: conn = wvmInstance(hostname, login, password, htype, name) vnc_websocket_port = conn.get_vnc_websocket_port() vnc_passwd = conn.get_vnc_passwd() except: vnc_websocket_port = None vnc_passwd = None ws_port = vnc_websocket_port if vnc_websocket_port else WS_PORT ws_host = request.get_host() if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) response = render_to_response('console.html', locals(), context_instance=RequestContext(request)) token = hostname + "|" + name + "|" + display des = DES() des.input_key(WS_DESKEY) encryptval = des.encode(token) response.set_cookie('token', encryptval) return response
def inst_graph(request, compute_id, vname): """ :param request: :return: """ datasets = {} json_blk = [] datasets_blk = {} json_net = [] datasets_net = {} cookies = {} points = 5 curent_time = time.strftime("%H:%M:%S") compute = get_object_or_404(Compute, pk=compute_id) response = HttpResponse() response['Content-Type'] = "text/javascript" def check_points(dataset): if len(dataset) > points: dataset.pop(0) return dataset try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) cpu_usage = conn.cpu_usage() blk_usage = conn.disk_usage() net_usage = conn.net_usage() conn.close() try: cookies['cpu'] = request.COOKIES['cpu'] cookies['blk'] = request.COOKIES['blk'] cookies['net'] = request.COOKIES['net'] cookies['timer'] = request.COOKIES['timer'] except KeyError: cookies['cpu'] = None cookies['blk'] = None cookies['net'] = None if not cookies['cpu']: datasets['cpu'] = [0] * points datasets['timer'] = [0] * points else: datasets['cpu'] = eval(cookies['cpu']) datasets['timer'] = eval(cookies['timer']) datasets['timer'].append(curent_time) datasets['cpu'].append(int(cpu_usage['cpu'])) datasets['timer'] = check_points(datasets['timer']) datasets['cpu'] = check_points(datasets['cpu']) for blk in blk_usage: if not cookies['blk']: datasets_wr = [0] * points datasets_rd = [0] * points else: datasets['blk'] = eval(cookies['blk']) datasets_rd = datasets['blk'][blk['dev']][0] datasets_wr = datasets['blk'][blk['dev']][1] datasets_rd.append(int(blk['rd']) / 1048576) datasets_wr.append(int(blk['wr']) / 1048576) datasets_rd = check_points(datasets_rd) datasets_wr = check_points(datasets_wr) json_blk.append({'dev': blk['dev'], 'data': [datasets_rd, datasets_wr]}) datasets_blk[blk['dev']] = [datasets_rd, datasets_wr] for net in net_usage: if not cookies['net']: datasets_rx = [0] * points datasets_tx = [0] * points else: datasets['net'] = eval(cookies['net']) datasets_rx = datasets['net'][net['dev']][0] datasets_tx = datasets['net'][net['dev']][1] datasets_rx.append(int(net['rx']) / 1048576) datasets_tx.append(int(net['tx']) / 1048576) datasets_rx = check_points(datasets_rx) datasets_tx = check_points(datasets_tx) json_net.append({'dev': net['dev'], 'data': [datasets_rx, datasets_tx]}) datasets_net[net['dev']] = [datasets_rx, datasets_tx] data = json.dumps({'cpudata': datasets['cpu'], 'blkdata': json_blk, 'netdata': json_net, 'timeline': datasets['timer']}) response.cookies['cpu'] = datasets['cpu'] response.cookies['timer'] = datasets['timer'] response.cookies['blk'] = datasets_blk response.cookies['net'] = datasets_net except libvirtError: data = json.dumps({'error': 'Error 500'}) response.write(data) return response
def instance(request, host_id, vname): """ Instance block """ def show_clone_disk(disks): clone_disk = [] for disk in disks: if disk['image'].count(".") and len(disk['image'].rsplit(".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append( {'dev': disk['dev'], 'storage': disk['storage'], 'image': image, 'format': disk['format']}) return clone_disk errors = [] messages = [] time_refresh = TIME_JS_REFRESH compute = Compute.objects.get(id=host_id) computes = Compute.objects.all() computes_count = len(computes) keymaps = QEMU_KEYMAPS try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 1024, 2048, 4096, 6144, 8192, 16384] memory_host = conn.get_max_memory() vcpu_host = len(vcpu_range) telnet_port = conn.get_telnet_port() vnc_port = conn.get_vnc_port() vnc_keymap = conn.get_vnc_keymap() vnc_password = conn.get_vnc_passwd() snapshots = sorted(conn.get_snapshot(), reverse=True) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks) cpu_usage = conn.cpu_usage()['cpu'] except libvirtError as err: errors.append(err) try: instance = Instance.objects.get(compute_id=host_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=host_id, name=vname, uuid=uuid) instance.save() try: if request.method == 'POST': if 'start' in request.POST: conn.start() return HttpResponseRedirect(request.get_full_path() + '#shutdown') if 'power' in request.POST: if 'shutdown' == request.POST.get('power', ''): conn.shutdown() return HttpResponseRedirect(request.get_full_path() + '#shutdown') if 'destroy' == request.POST.get('power', ''): conn.force_shutdown() return HttpResponseRedirect(request.get_full_path() + '#forceshutdown') if 'managedsave' == request.POST.get('power', ''): conn.managedsave() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'deletesaveimage' in request.POST: conn.managed_save_remove() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'suspend' in request.POST: conn.suspend() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'resume' in request.POST: conn.resume() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() if request.POST.get('delete_disk', ''): print 'yeah' conn.delete_disk() try: instance = Instance.objects.get(compute_id=host_id, name=vname) instance.delete() finally: conn.delete() return HttpResponseRedirect('/%s/instances' % host_id) if 'assign_volume' in request.POST: file = request.POST.get('file', '') device = request.POST.get('device', '') conn.assign_volume(file, device) return HttpResponseRedirect(request.get_full_path() + '#instancedevice') if 'unassign_volume' in request.POST: device = request.POST.get('device', '') conn.unassign_volume(device) return HttpResponseRedirect(request.get_full_path() + '#instancedevice') if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'external_storage_snapshot' in request.POST: name = request.POST.get('name', '') conn.create_external_storage_snapshot(name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'umount_iso' in request.POST: image = request.POST.get('path', '') first_cd = media[0]['dev'] if len(media) > 0 else request.POST.get('umount_iso', '') dev = request.POST.get('device', first_cd) conn.umount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'mount_iso' in request.POST: image = request.POST.get('media', '') first_cd = media[0]['dev'] if len(media) > 0 else '' print first_cd dev = request.POST.get('device', first_cd) conn.mount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'set_autostart' in request.POST: conn.set_autostart(1) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'unset_autostart' in request.POST: conn.set_autostart(0) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_settings' in request.POST: description = request.POST.get('description', '') vcpu = request.POST.get('vcpu', '') cur_vcpu = request.POST.get('cur_vcpu', '') memory = request.POST.get('memory', '') cur_memory = request.POST.get('cur_memory', '') conn.change_settings(description, cur_memory, memory, cur_vcpu, vcpu) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_xml' in request.POST: xml = request.POST.get('inst_xml', '') if xml: conn._defineXML(xml) return HttpResponseRedirect(request.get_full_path() + '#instancexml') if 'set_vnc_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join([choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('vnc_passwd', '') clear = request.POST.get('clear_pass', False) if not passwd and not clear: msg = _("Enter the VNC password or select Generate") errors.append(msg) if not errors: conn.set_vnc_passwd(passwd) return HttpResponseRedirect(request.get_full_path() + '#vnc_pass') if 'set_vnc_keymap' in request.POST: keymap = request.POST.get('vnc_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_vnc_keymap('') else: conn.set_vnc_keymap(keymap) return HttpResponseRedirect(request.get_full_path() + '#vnc_keymap') if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') live = request.POST.get('live_migrate', False) unsafe = request.POST.get('unsafe_migrate', False) xml_del = request.POST.get('xml_delete', False) new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname, live, unsafe, xml_del) conn_migrate.define_move(vname) conn_migrate.close() return HttpResponseRedirect('/%s/instance/%s' % (compute_id, vname)) if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') for post in request.POST: if 'disk' or 'meta' in post: clone_data[post] = request.POST.get(post, '') conn.clone_instance(clone_data) return HttpResponseRedirect('/%s/instance/%s' % (host_id, clone_data['name'])) conn.close() except libvirtError as err: errors.append(err) object = { 'errors': [str(error) for error in errors], 'response': { 'name': vname, 'status': status, 'autostart': autostart, 'vcpu': vcpu, 'cur_vcpu': cur_vcpu, 'uuid': uuid, 'memory': memory, 'cur_memory': cur_memory, 'description': description, 'disks': disks, 'media': media, 'networks': networks, 'media_iso': media_iso, 'vcpu_range': vcpu_range.__len__(), 'memory_host': memory_host, 'vcpu_host': vcpu_host, 'telnet_port': telnet_port, 'vnc_port': vnc_port, 'vnc_keymap': vnc_keymap, 'snapshots': snapshots, 'inst_xml': inst_xml.__str__(), 'has_managed_save_image': has_managed_save_image, 'clone_disks': clone_disks, 'cpu_usage': cpu_usage, 'vnc_password': vnc_password } } return render(object, 'instance.html', locals(), request)
def diskusage(request, host_id, vname): """ VM disk IO """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') datasets_rd = [] datasets_wr = [] json_blk = [] cookie_blk = {} compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) blk_usage = conn.disk_usage() conn.close() except libvirtError: blk_usage = None try: cookies = request._cookies['blk_usage'] except KeyError: cookies = None for blk in blk_usage: if not cookies: datasets_wr.append(0) datasets_rd.append(0) else: datasets = eval(cookies) datasets_rd = datasets[blk['dev']][0] datasets_wr = datasets[blk['dev']][1] if len(datasets_rd) > 10: while datasets_rd: del datasets_rd[0] if len(datasets_rd) == 10: break if len(datasets_wr) > 10: while datasets_wr: del datasets_wr[0] if len(datasets_wr) == 10: break if len(datasets_rd) <= 9: datasets_rd.append(int(blk['rd']) / 1048576) if len(datasets_rd) == 10: datasets_rd.append(int(blk['rd']) / 1048576) del datasets_rd[0] if len(datasets_wr) <= 9: datasets_wr.append(int(blk['wr']) / 1048576) if len(datasets_wr) == 10: datasets_wr.append(int(blk['wr']) / 1048576) del datasets_wr[0] disk = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rd }, { "fillColor": "rgba(249,134,33,0.5)", "strokeColor": "rgba(249,134,33,1)", "pointColor": "rgba(249,134,33,1)", "pointStrokeColor": "#fff", "data": datasets_wr }, ] } json_blk.append({'dev': blk['dev'], 'data': disk}) cookie_blk[blk['dev']] = [datasets_rd, datasets_wr] data = simplejson.dumps(json_blk) response = HttpResponse() response['Content-Type'] = "text/javascript" response.cookies['blk_usage'] = cookie_blk response.write(data) return response
def instusage(request, host_id, vname): """ Return instance usage """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') cookies = {} datasets = {} datasets_rd = [] datasets_wr = [] json_blk = [] cookie_blk = {} blk_error = False datasets_rx = [] datasets_tx = [] json_net = [] cookie_net = {} net_error = False networks = None disks = None compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() if status == 5: networks = conn.get_net_device() disks = conn.get_disk_device() except libvirtError: status = None if status == 1 and status: try: blk_usage = conn.disk_usage() cpu_usage = conn.cpu_usage() net_usage = conn.net_usage() conn.close() except libvirtError: blk_usage = None cpu_usage = None net_usage = None try: cookies['cpu'] = request._cookies['cpu'] except KeyError: cookies['cpu'] = None try: cookies['hdd'] = request._cookies['hdd'] except KeyError: cookies['hdd'] = None try: cookies['net'] = request._cookies['net'] except KeyError: cookies['net'] = None if cookies['cpu'] == '{}' or not cookies['cpu'] or not cpu_usage: datasets['cpu'] = [0] else: datasets['cpu'] = eval(cookies['cpu']) if len(datasets['cpu']) > 10: while datasets['cpu']: del datasets['cpu'][0] if len(datasets['cpu']) == 10: break if len(datasets['cpu']) <= 9: datasets['cpu'].append(int(cpu_usage['cpu'])) if len(datasets['cpu']) == 10: datasets['cpu'].append(int(cpu_usage['cpu'])) del datasets['cpu'][0] # Some fix division by 0 Chart.js if len(datasets['cpu']) == 10: if sum(datasets['cpu']) == 0: datasets['cpu'][9] += 0.1 if sum(datasets['cpu']) / 10 == datasets['cpu'][0]: datasets['cpu'][9] += 0.1 cpu = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(241,72,70,0.5)", "strokeColor": "rgba(241,72,70,1)", "pointColor": "rgba(241,72,70,1)", "pointStrokeColor": "#fff", "data": datasets['cpu'] } ] } for blk in blk_usage: if cookies['hdd'] == '{}' or not cookies['hdd'] or not blk_usage: datasets_wr.append(0) datasets_rd.append(0) else: datasets['hdd'] = eval(cookies['hdd']) try: datasets_rd = datasets['hdd'][blk['dev']][0] datasets_wr = datasets['hdd'][blk['dev']][1] except: blk_error = True if not blk_error: if len(datasets_rd) > 10: while datasets_rd: del datasets_rd[0] if len(datasets_rd) == 10: break if len(datasets_wr) > 10: while datasets_wr: del datasets_wr[0] if len(datasets_wr) == 10: break if len(datasets_rd) <= 9: datasets_rd.append(int(blk['rd']) / 1048576) if len(datasets_rd) == 10: datasets_rd.append(int(blk['rd']) / 1048576) del datasets_rd[0] if len(datasets_wr) <= 9: datasets_wr.append(int(blk['wr']) / 1048576) if len(datasets_wr) == 10: datasets_wr.append(int(blk['wr']) / 1048576) del datasets_wr[0] # Some fix division by 0 Chart.js if len(datasets_rd) == 10: if sum(datasets_rd) == 0: datasets_rd[9] += 0.01 if sum(datasets_rd) / 10 == datasets_rd[0]: datasets_rd[9] += 0.01 disk = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rd }, { "fillColor": "rgba(249,134,33,0.5)", "strokeColor": "rgba(249,134,33,1)", "pointColor": "rgba(249,134,33,1)", "pointStrokeColor": "#fff", "data": datasets_wr }, ] } json_blk.append({'dev': blk['dev'], 'data': disk}) cookie_blk[blk['dev']] = [datasets_rd, datasets_wr] for net in net_usage: if cookies['net'] == '{}' or not cookies['net'] or not net_usage: datasets_rx.append(0) datasets_tx.append(0) else: datasets['net'] = eval(cookies['net']) try: datasets_rx = datasets['net'][net['dev']][0] datasets_tx = datasets['net'][net['dev']][1] except: net_error = True if not net_error: if len(datasets_rx) > 10: while datasets_rx: del datasets_rx[0] if len(datasets_rx) == 10: break if len(datasets_tx) > 10: while datasets_tx: del datasets_tx[0] if len(datasets_tx) == 10: break if len(datasets_rx) <= 9: datasets_rx.append(int(net['rx']) / 1048576) if len(datasets_rx) == 10: datasets_rx.append(int(net['rx']) / 1048576) del datasets_rx[0] if len(datasets_tx) <= 9: datasets_tx.append(int(net['tx']) / 1048576) if len(datasets_tx) == 10: datasets_tx.append(int(net['tx']) / 1048576) del datasets_tx[0] # Some fix division by 0 Chart.js if len(datasets_rx) == 10: if sum(datasets_rx) == 0: datasets_rx[9] += 0.01 if sum(datasets_rx) / 10 == datasets_rx[0]: datasets_rx[9] += 0.01 network = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rx }, { "fillColor": "rgba(151,187,205,0.5)", "strokeColor": "rgba(151,187,205,1)", "pointColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": datasets_tx }, ] } json_net.append({'dev': net['dev'], 'data': network}) cookie_net[net['dev']] = [datasets_rx, datasets_tx] data = json.dumps({'status': status, 'cpu': cpu, 'hdd': json_blk, 'net': json_net}) else: datasets = [0] * 10 cpu = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(241,72,70,0.5)", "strokeColor": "rgba(241,72,70,1)", "pointColor": "rgba(241,72,70,1)", "pointStrokeColor": "#fff", "data": datasets } ] } for i, net in enumerate(networks): datasets_rx = [0] * 10 datasets_tx = [0] * 10 network = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rx }, { "fillColor": "rgba(151,187,205,0.5)", "strokeColor": "rgba(151,187,205,1)", "pointColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": datasets_tx }, ] } json_net.append({'dev': i, 'data': network}) for blk in disks: datasets_wr = [0] * 10 datasets_rd = [0] * 10 disk = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rd }, { "fillColor": "rgba(249,134,33,0.5)", "strokeColor": "rgba(249,134,33,1)", "pointColor": "rgba(249,134,33,1)", "pointStrokeColor": "#fff", "data": datasets_wr }, ] } json_blk.append({'dev': blk['dev'], 'data': disk}) data = json.dumps({'status': status, 'cpu': cpu, 'hdd': json_blk, 'net': json_net}) response = HttpResponse() response['Content-Type'] = "text/javascript" if status == 1: response.cookies['cpu'] = datasets['cpu'] response.cookies['hdd'] = cookie_blk response.cookies['net'] = cookie_net response.write(data) return response
def instance(request, compute_id, vname): """ :param request: :return: """ error_messages = [] messages = [] compute = get_object_or_404(Compute, pk=compute_id) computes = Compute.objects.all().order_by('name') computes_count = computes.count() users = User.objects.all().order_by('username') publickeys = UserSSHKey.objects.filter(user_id=request.user.id) keymaps = settings.QEMU_KEYMAPS console_types = settings.QEMU_CONSOLE_TYPES console_listen_addresses = settings.QEMU_CONSOLE_LISTEN_ADDRESSES try: userinstace = UserInstance.objects.get(instance__compute_id=compute_id, instance__name=vname, user__id=request.user.id) except UserInstance.DoesNotExist: userinstace = None if not request.user.is_superuser: if not userinstace: return HttpResponseRedirect(reverse('index')) def show_clone_disk(disks, vname=''): clone_disk = [] for disk in disks: if disk['image'] is None: continue if disk['image'].count("-") and disk['image'].rsplit( "-", 1)[0] == vname: name, suffix = disk['image'].rsplit("-", 1) image = name + "-clone" + "-" + suffix elif disk['image'].count(".") and len(disk['image'].rsplit( ".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append({ 'dev': disk['dev'], 'storage': disk['storage'], 'image': image, 'format': disk['format'] }) return clone_disk def filesizefstr(size_str): if size_str == '': return 0 size_str = size_str.encode('ascii', 'ignore').upper().translate(None, " B") if 'K' == size_str[-1]: return long(float(size_str[:-1])) << 10 elif 'M' == size_str[-1]: return long(float(size_str[:-1])) << 20 elif 'G' == size_str[-1]: return long(float(size_str[:-1])) << 30 elif 'T' == size_str[-1]: return long(float(size_str[:-1])) << 40 elif 'P' == size_str[-1]: return long(float(size_str[:-1])) << 50 else: return long(float(size_str)) def get_clone_free_names(size=10): prefix = settings.CLONE_INSTANCE_DEFAULT_PREFIX free_names = [] existing_names = [ i.name for i in Instance.objects.filter(name__startswith=prefix) ] index = 1 while len(free_names) < size: new_name = prefix + str(index) if new_name not in existing_names: free_names.append(new_name) index += 1 return free_names def check_user_quota(instance, cpu, memory, disk_size): user_instances = UserInstance.objects.filter( user_id=request.user.id, instance__is_template=False) instance += user_instances.count() for usr_inst in user_instances: if connection_manager.host_is_up( usr_inst.instance.compute.type, usr_inst.instance.compute.hostname): conn = wvmInstance(usr_inst.instance.compute, usr_inst.instance.compute.login, usr_inst.instance.compute.password, usr_inst.instance.compute.type, usr_inst.instance.name) cpu += int(conn.get_vcpu()) memory += int(conn.get_memory()) for disk in conn.get_disk_device(): if disk['size']: disk_size += int(disk['size']) >> 30 ua = request.user.userattributes msg = "" if ua.max_instances > 0 and instance > ua.max_instances: msg = "instance" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (instance, ua.max_instances) if ua.max_cpus > 0 and cpu > ua.max_cpus: msg = "cpu" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (cpu, ua.max_cpus) if ua.max_memory > 0 and memory > ua.max_memory: msg = "memory" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (memory, ua.max_memory) if ua.max_disk_size > 0 and disk_size > ua.max_disk_size: msg = "disk" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (disk_size, ua.max_disk_size) return msg def get_new_disk_dev(disks, bus): if bus == "virtio": dev_base = "vd" else: dev_base = "sd" existing_devs = [disk['dev'] for disk in disks] for l in string.lowercase: dev = dev_base + l if dev not in existing_devs: return dev raise Exception(_('None available device name')) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() title = conn.get_title() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() if len(media) != 0: media_iso = sorted(conn.get_iso_media()) else: media_iso = [] vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 768, 1024, 2048, 4096, 6144, 8192, 16384] if memory not in memory_range: insort(memory_range, memory) if cur_memory not in memory_range: insort(memory_range, cur_memory) memory_host = conn.get_max_memory() vcpu_host = len(vcpu_range) telnet_port = conn.get_telnet_port() console_type = conn.get_console_type() console_port = conn.get_console_port() console_keymap = conn.get_console_keymap() snapshots = sorted(conn.get_snapshot(), reverse=True, key=lambda k: k['date']) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks, vname) console_passwd = conn.get_console_passwd() clone_free_names = get_clone_free_names() user_quota_msg = check_user_quota(0, 0, 0, 0) storages = sorted(conn.get_storages()) cache_modes = sorted(conn.get_cache_modes().items()) default_cache = settings.INSTANCE_VOLUME_DEFAULT_CACHE default_format = settings.INSTANCE_VOLUME_DEFAULT_FORMAT formats = conn.get_image_formats() busses = conn.get_busses() default_bus = settings.INSTANCE_VOLUME_DEFAULT_BUS show_access_root_password = settings.SHOW_ACCESS_ROOT_PASSWORD show_access_ssh_keys = settings.SHOW_ACCESS_SSH_KEYS try: instance = Instance.objects.get(compute_id=compute_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=compute_id, name=vname, uuid=uuid) instance.save() userinstances = UserInstance.objects.filter( instance=instance).order_by('user__username') if request.method == 'POST': if 'poweron' in request.POST: conn.start() msg = _("Power On") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#poweron') if 'powercycle' in request.POST: conn.force_shutdown() conn.start() msg = _("Power Cycle") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#powercycle') if 'poweroff' in request.POST: conn.shutdown() msg = _("Power Off") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#poweroff') if 'powerforce' in request.POST: conn.force_shutdown() msg = _("Force Off") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#powerforce') if 'delete' in request.POST and (request.user.is_superuser or userinstace.is_delete): if conn.get_status() == 1: conn.force_shutdown() if request.POST.get('delete_disk', ''): for snap in snapshots: conn.snapshot_delete(snap['name']) conn.delete_disk() conn.delete() instance = Instance.objects.get(compute_id=compute_id, name=vname) instance_name = instance.name instance.delete() try: del_userinstance = UserInstance.objects.filter( instance__compute_id=compute_id, instance__name=vname) del_userinstance.delete() except UserInstance.DoesNotExist: pass msg = _("Destroy") addlogmsg(request.user.username, instance_name, msg) return HttpResponseRedirect(reverse('instances')) if 'rootpasswd' in request.POST: passwd = request.POST.get('passwd', '') passwd_hash = crypt.crypt(passwd, '$6$kgPoiREy') data = { 'action': 'password', 'passwd': passwd_hash, 'vname': vname } if conn.get_status() == 5: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((compute.hostname, 16510)) s.send(json.dumps(data)) result = json.loads(s.recv(1024)) s.close() msg = _("Reset root password") addlogmsg(request.user.username, instance.name, msg) if result['return'] == 'success': messages.append(msg) else: error_messages.append(msg) else: msg = _( "Please shutdow down your instance and then try again") error_messages.append(msg) if 'addpublickey' in request.POST: sshkeyid = request.POST.get('sshkeyid', '') publickey = UserSSHKey.objects.get(id=sshkeyid) data = { 'action': 'publickey', 'key': publickey.keypublic, 'vname': vname } if conn.get_status() == 5: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((compute.hostname, 16510)) s.send(json.dumps(data)) result = json.loads(s.recv(1024)) s.close() msg = _("Installed new ssh public key %s" % publickey.keyname) addlogmsg(request.user.username, instance.name, msg) if result['return'] == 'success': messages.append(msg) else: error_messages.append(msg) else: msg = _( "Please shutdow down your instance and then try again") error_messages.append(msg) if 'resize' in request.POST and (request.user.is_superuser or request.user.is_staff or userinstace.is_change): new_vcpu = request.POST.get('vcpu', '') new_cur_vcpu = request.POST.get('cur_vcpu', '') new_memory = request.POST.get('memory', '') new_memory_custom = request.POST.get('memory_custom', '') if new_memory_custom: new_memory = new_memory_custom new_cur_memory = request.POST.get('cur_memory', '') new_cur_memory_custom = request.POST.get( 'cur_memory_custom', '') if new_cur_memory_custom: new_cur_memory = new_cur_memory_custom disks_new = [] for disk in disks: input_disk_size = filesizefstr( request.POST.get('disk_size_' + disk['dev'], '')) if input_disk_size > disk['size'] + (64 << 20): disk['size_new'] = input_disk_size disks_new.append(disk) disk_sum = sum([disk['size'] >> 30 for disk in disks_new]) disk_new_sum = sum( [disk['size_new'] >> 30 for disk in disks_new]) quota_msg = check_user_quota(0, int(new_vcpu) - vcpu, int(new_memory) - memory, disk_new_sum - disk_sum) if not request.user.is_superuser and quota_msg: msg = _("User %s quota reached, cannot resize '%s'!" % (quota_msg, instance.name)) error_messages.append(msg) else: cur_memory = new_cur_memory memory = new_memory cur_vcpu = new_cur_vcpu vcpu = new_vcpu conn.resize(cur_memory, memory, cur_vcpu, vcpu, disks_new) msg = _("Resize") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#resize') if 'addvolume' in request.POST and (request.user.is_superuser or userinstace.is_change): connCreate = wvmCreate(compute.hostname, compute.login, compute.password, compute.type) storage = request.POST.get('storage', '') name = request.POST.get('name', '') extension = request.POST.get('extension', '') format = request.POST.get('format', '') size = request.POST.get('size', 0) meta_prealloc = request.POST.get('meta_prealloc', False) bus = request.POST.get('bus', '') cache = request.POST.get('cache', '') target = get_new_disk_dev(disks, bus) path = connCreate.create_volume(storage, name, size, format, meta_prealloc, extension) conn.attach_disk(path, target, subdriver=format, cache=cache, targetbus=bus) msg = _('Attach new disk') addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#resize') if 'umount_iso' in request.POST: image = request.POST.get('path', '') dev = request.POST.get('umount_iso', '') conn.umount_iso(dev, image) msg = _("Mount media") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#media') if 'mount_iso' in request.POST: image = request.POST.get('media', '') dev = request.POST.get('mount_iso', '') conn.mount_iso(dev, image) msg = _("Umount media") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#media') if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) msg = _("New snapshot") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#restoresnapshot') if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) msg = _("Delete snapshot") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#restoresnapshot') if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) msg = _("Revert snapshot") addlogmsg(request.user.username, instance.name, msg) if request.user.is_superuser: if 'suspend' in request.POST: conn.suspend() msg = _("Suspend") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#resume') if 'resume' in request.POST: conn.resume() msg = _("Resume") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'set_autostart' in request.POST: conn.set_autostart(1) msg = _("Set autostart") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#autostart') if 'unset_autostart' in request.POST: conn.set_autostart(0) msg = _("Unset autostart") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#autostart') if 'change_xml' in request.POST: exit_xml = request.POST.get('inst_xml', '') if exit_xml: conn._defineXML(exit_xml) msg = _("Edit XML") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#xmledit') if request.user.is_superuser or userinstace.is_vnc: if 'set_console_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = randomPasswd() else: passwd = request.POST.get('console_passwd', '') clear = request.POST.get('clear_pass', False) if clear: passwd = '' if not passwd and not clear: msg = _( "Enter the console password or select Generate" ) error_messages.append(msg) if not error_messages: if not conn.set_console_passwd(passwd): msg = _( "Error setting console password. You should check that your instance have an graphic device." ) error_messages.append(msg) else: msg = _("Set VNC password") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect( request.get_full_path() + '#vncsettings') if 'set_console_keymap' in request.POST: keymap = request.POST.get('console_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_console_keymap('') else: conn.set_console_keymap(keymap) msg = _("Set VNC keymap") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if 'set_console_type' in request.POST: console_type = request.POST.get('console_type', '') conn.set_console_type(console_type) msg = _("Set VNC type") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if 'set_console_listen_address' in request.POST: console_type = request.POST.get('console_listen_address', '') conn.set_console_listen_addr(console_type) msg = _("Set VNC listen address") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if request.user.is_superuser: if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') live = request.POST.get('live_migrate', False) unsafe = request.POST.get('unsafe_migrate', False) xml_del = request.POST.get('xml_delete', False) offline = request.POST.get('offline_migrate', False) new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname, live, unsafe, xml_del, offline) instance.compute = new_compute instance.save() conn_migrate.close() if autostart: conn_new = wvmInstance(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type, vname) conn_new.set_autostart(1) conn_new.close() msg = _("Migrate to %s" % new_compute.hostname) addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect( reverse('instance', args=[compute_id, vname])) if 'change_network' in request.POST: network_data = {} for post in request.POST: if post.startswith('net-'): network_data[post] = request.POST.get(post, '') conn.change_network(network_data) msg = _("Edit network") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#network') if 'add_owner' in request.POST: user_id = int(request.POST.get('user_id', '')) if settings.ALLOW_INSTANCE_MULTIPLE_OWNER: check_inst = UserInstance.objects.filter( instance=instance, user_id=user_id) else: check_inst = UserInstance.objects.filter( instance=instance) if check_inst: msg = _("Owner already added") error_messages.append(msg) else: add_user_inst = UserInstance(instance=instance, user_id=user_id) add_user_inst.save() msg = _("Added owner %d" % user_id) addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#users') if 'del_owner' in request.POST: userinstance_id = int(request.POST.get('userinstance', '')) userinstance = UserInstance.objects.get(pk=userinstance_id) userinstance.delete() msg = _("Deleted owner %d" % userinstance_id) addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#users') if request.user.is_superuser or request.user.userattributes.can_clone_instances: if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') disk_sum = sum([disk['size'] >> 30 for disk in disks]) quota_msg = check_user_quota(1, vcpu, memory, disk_sum) check_instance = Instance.objects.filter( name=clone_data['name']) for post in request.POST: clone_data[post] = request.POST.get(post, '').strip() if not request.user.is_superuser and quota_msg: msg = _("User %s quota reached, cannot create '%s'!" % (quota_msg, clone_data['name'])) error_messages.append(msg) elif check_instance: msg = _("Instance '%s' already exists!" % clone_data['name']) error_messages.append(msg) elif not re.match(r'^[a-zA-Z0-9-]+$', clone_data['name']): msg = _( "Instance name '%s' contains invalid characters!" % clone_data['name']) error_messages.append(msg) elif not re.match(r'^([0-9A-F]{2})(\:?[0-9A-F]{2}){5}$', clone_data['clone-net-mac-0'], re.IGNORECASE): msg = _("Instance mac '%s' invalid format!" % clone_data['clone-net-mac-0']) error_messages.append(msg) else: new_uuid = conn.clone_instance(clone_data) new_instance = Instance(compute_id=compute_id, name=clone_data['name'], uuid=new_uuid) new_instance.save() userinstance = UserInstance( instance_id=new_instance.id, user_id=request.user.id, is_delete=True) userinstance.save() msg = _("Clone of '%s'" % instance.name) addlogmsg(request.user.username, new_instance.name, msg) return HttpResponseRedirect( reverse('instance', args=[compute_id, clone_data['name']])) if 'change_options' in request.POST: instance.is_template = request.POST.get( 'is_template', False) instance.save() options = {} for post in request.POST: if post in ['title', 'description']: options[post] = request.POST.get(post, '') conn.set_options(options) msg = _("Edit options") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#options') conn.close() except libvirtError as lib_err: error_messages.append(lib_err.message) addlogmsg(request.user.username, vname, lib_err.message) return render(request, 'instance.html', locals())
def instance(request, compute_id, vname): """ :param request: :return: """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('index')) error_messages = [] messages = [] compute = get_object_or_404(Compute, pk=compute_id) computes = Compute.objects.all() computes_count = len(computes) publickeys = UserSSHKey.objects.filter(user_id=request.user.id) keymaps = QEMU_KEYMAPS console_types = QEMU_CONSOLE_TYPES try: userinstace = UserInstance.objects.get(instance__compute_id=compute_id, instance__name=vname, user__id=request.user.id) except UserInstance.DoesNotExist: userinstace = None if not request.user.is_superuser: if not userinstace: return HttpResponseRedirect(reverse('index')) def show_clone_disk(disks): clone_disk = [] for disk in disks: if disk['image'] is None: continue if disk['image'].count(".") and len(disk['image'].rsplit( ".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append({ 'dev': disk['dev'], 'storage': disk['storage'], 'image': image, 'format': disk['format'] }) return clone_disk try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 768, 1024, 2048, 4096, 6144, 8192, 16384] if memory not in memory_range: insort(memory_range, memory) if cur_memory not in memory_range: insort(memory_range, cur_memory) memory_host = conn.get_max_memory() vcpu_host = len(vcpu_range) telnet_port = conn.get_telnet_port() console_type = conn.get_console_type() console_port = conn.get_console_port() console_keymap = conn.get_console_keymap() snapshots = sorted(conn.get_snapshot(), reverse=True) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks) console_passwd = conn.get_console_passwd() try: instance = Instance.objects.get(compute_id=compute_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=compute_id, name=vname, uuid=uuid) instance.save() if request.method == 'POST': if 'poweron' in request.POST: conn.start() msg = _("Power On") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#poweron') if 'powercycle' in request.POST: conn.force_shutdown() conn.start() msg = _("Power Cycle") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#powercycle') if 'poweroff' in request.POST: conn.shutdown() msg = _("Power Off") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#poweroff') if 'powerforce' in request.POST: conn.force_shutdown() msg = _("Force Off") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#powerforce') if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() if request.POST.get('delete_disk', ''): conn.delete_disk() conn.delete() instance = Instance.objects.get(compute_id=compute_id, name=vname) instance_name = instance.name instance.delete() if not request.user.is_superuser: del_userinstance = UserInstance.objects.get( id=userinstace.id) del_userinstance.delete() else: try: del_userinstance = UserInstance.objects.filter( instance__compute_id=compute_id, instance__name=vname) del_userinstance.delete() except UserInstance.DoesNotExist: pass msg = _("Destroy") addlogmsg(request.user.username, instance_name, msg) return HttpResponseRedirect(reverse('instances')) if 'rootpasswd' in request.POST: passwd = request.POST.get('passwd', '') passwd_hash = crypt.crypt(passwd, '$6$kgPoiREy') data = { 'action': 'password', 'passwd': passwd_hash, 'vname': vname } if conn.get_status() == 5: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((compute.hostname, 16510)) s.send(json.dumps(data)) result = json.loads(s.recv(1024)) s.close() msg = _("Reset root password") addlogmsg(request.user.username, instance.name, msg) if result['return'] == 'success': messages.append(msg) else: error_messages.append(msg) else: msg = _( "Please shutdow down your instance and then try again") error_messages.append(msg) if 'addpublickey' in request.POST: sshkeyid = request.POST.get('sshkeyid', '') publickey = UserSSHKey.objects.get(id=sshkeyid) data = { 'action': 'publickey', 'key': publickey.keypublic, 'vname': vname } if conn.get_status() == 5: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((compute.hostname, 16510)) s.send(json.dumps(data)) result = json.loads(s.recv(1024)) s.close() msg = _("Installed new ssh public key %s" % publickey.keyname) addlogmsg(request.user.username, instance.name, msg) if result['return'] == 'success': messages.append(msg) else: error_messages.append(msg) else: msg = _( "Please shutdow down your instance and then try again") error_messages.append(msg) if 'resize' in request.POST: vcpu = request.POST.get('vcpu', '') cur_vcpu = request.POST.get('cur_vcpu', '') memory = request.POST.get('memory', '') memory_custom = request.POST.get('memory_custom', '') if memory_custom: memory = memory_custom cur_memory = request.POST.get('cur_memory', '') cur_memory_custom = request.POST.get('cur_memory_custom', '') if cur_memory_custom: cur_memory = cur_memory_custom conn.resize(cur_memory, memory, cur_vcpu, vcpu) msg = _("Resize") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#resize') if 'umount_iso' in request.POST: image = request.POST.get('path', '') dev = request.POST.get('umount_iso', '') conn.umount_iso(dev, image) msg = _("Mount media") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#media') if 'mount_iso' in request.POST: image = request.POST.get('media', '') dev = request.POST.get('mount_iso', '') conn.mount_iso(dev, image) msg = _("Umount media") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#media') if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) msg = _("New snapshot") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#restoresnapshot') if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) msg = _("Delete snapshot") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#restoresnapshot') if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) msg = _("Revert snapshot") addlogmsg(request.user.username, instance.name, msg) if request.user.is_superuser: if 'suspend' in request.POST: conn.suspend() msg = _("Suspend") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#resume') if 'resume' in request.POST: conn.resume() msg = _("Resume") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'set_autostart' in request.POST: conn.set_autostart(1) msg = _("Set autostart") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#autostart') if 'unset_autostart' in request.POST: conn.set_autostart(0) msg = _("Unset autostart") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#autostart') if 'change_xml' in request.POST: exit_xml = request.POST.get('inst_xml', '') if exit_xml: conn._defineXML(exit_xml) msg = _("Edit XML") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#xmledit') if 'set_console_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join( [choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('console_passwd', '') clear = request.POST.get('clear_pass', False) if clear: passwd = '' if not passwd and not clear: msg = _( "Enter the console password or select Generate" ) error_messages.append(msg) if not error_messages: if not conn.set_console_passwd(passwd): msg = _( "Error setting console password. You should check that your instance have an graphic device." ) error_messages.append(msg) else: msg = _("Set VNC password") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect( request.get_full_path() + '#vncsettings') if 'set_console_keymap' in request.POST: keymap = request.POST.get('console_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_console_keymap('') else: conn.set_console_keymap(keymap) msg = _("Set VNC keymap") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if 'set_console_type' in request.POST: console_type = request.POST.get('console_type', '') conn.set_console_type(console_type) msg = _("Set VNC type") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') live = request.POST.get('live_migrate', False) unsafe = request.POST.get('unsafe_migrate', False) xml_del = request.POST.get('xml_delete', False) new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname, live, unsafe, xml_del) conn_migrate.define_move(vname) conn_migrate.close() msg = _("Migrate") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect( reverse('instance', args=[compute_id, vname])) if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') for post in request.POST: if 'disk' or 'meta' in post: clone_data[post] = request.POST.get(post, '') conn.clone_instance(clone_data) msg = _("Clone") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect( reverse('instance', args=[compute_id, clone_data['name']])) conn.close() except libvirtError as lib_err: error_messages.append(lib_err.message) addlogmsg(request.user.username, vname, lib_err.message) return render(request, 'instance.html', locals())
def instances(request, host_id): """ Instances block """ errors = [] instances = [] time_refresh = 8000 get_instances = [] conn = None compute = Compute.objects.get(id=host_id) try: conn = wvmInstances(compute.hostname, compute.login, compute.password, compute.type) get_instances = conn.get_instances() except libvirtError as err: 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() conn2 = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, instance) instances.append({'name': instance, 'status': conn.get_instance_status(instance), 'uuid': uuid, 'memory': conn.get_instance_memory(instance), 'vcpu': conn.get_instance_vcpu(instance), 'storage': conn2.get_disk_device(), 'has_managed_save_image': conn.get_instance_managed_save_image(instance)}) conn2.close() 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()) conn.close() except libvirtError as err: errors.append(err) object = { 'response': { 'instances': instances }, 'errors': [str(error) for error in errors] } return render(object, 'instances.html', locals(), request)
def instusage(request, host_id, vname): """ Return instance usage """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) cookies = {} datasets = {} datasets_rd = [] datasets_wr = [] json_blk = [] cookie_blk = {} blk_error = False datasets_rx = [] datasets_tx = [] json_net = [] cookie_net = {} net_error = False points = 5 curent_time = time.strftime("%H:%M:%S") compute = Compute.objects.get(id=host_id) cookies = request._get_cookies() response = HttpResponse() response['Content-Type'] = "text/javascript" try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) cpu_usage = conn.cpu_usage() blk_usage = conn.disk_usage() net_usage = conn.net_usage() conn.close() if cookies.get('cpu') == '{}' or not cookies.get('cpu') or not cpu_usage: datasets['cpu'] = [0] datasets['timer'] = [curent_time] else: datasets['cpu'] = eval(cookies.get('cpu')) datasets['timer'] = eval(cookies.get('timer')) datasets['timer'].append(curent_time) datasets['cpu'].append(int(cpu_usage['cpu'])) if len(datasets['timer']) > points: datasets['timer'].pop(0) if len(datasets['cpu']) > points: datasets['cpu'].pop(0) cpu = { 'labels': datasets['timer'], 'datasets': [ { "fillColor": "rgba(241,72,70,0.5)", "strokeColor": "rgba(241,72,70,1)", "pointColor": "rgba(241,72,70,1)", "pointStrokeColor": "#fff", "data": datasets['cpu'] } ] } for blk in blk_usage: if cookies.get('hdd') == '{}' or not cookies.get('hdd') or not blk_usage: datasets_wr.append(0) datasets_rd.append(0) else: datasets['hdd'] = eval(cookies.get('hdd')) try: datasets_rd = datasets['hdd'][blk['dev']][0] datasets_wr = datasets['hdd'][blk['dev']][1] except: blk_error = True if not blk_error: datasets_rd.append(int(blk['rd']) / 1048576) datasets_wr.append(int(blk['wr']) / 1048576) if len(datasets_rd) > points: datasets_rd.pop(0) if len(datasets_wr) > points: datasets_wr.pop(0) disk = { 'labels': datasets['timer'], 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rd }, { "fillColor": "rgba(249,134,33,0.5)", "strokeColor": "rgba(249,134,33,1)", "pointColor": "rgba(249,134,33,1)", "pointStrokeColor": "#fff", "data": datasets_wr }, ] } json_blk.append({'dev': blk['dev'], 'data': disk}) cookie_blk[blk['dev']] = [datasets_rd, datasets_wr] for net in net_usage: if cookies.get('net') == '{}' or not cookies.get('net') or not net_usage: datasets_rx.append(0) datasets_tx.append(0) else: datasets['net'] = eval(cookies.get('net')) try: datasets_rx = datasets['net'][net['dev']][0] datasets_tx = datasets['net'][net['dev']][1] except: net_error = True if not net_error: datasets_rx.append(int(net['rx']) / 1048576) datasets_tx.append(int(net['tx']) / 1048576) if len(datasets_rx) > points: datasets_rx.pop(0) if len(datasets_tx) > points: datasets_tx.pop(0) network = { 'labels': datasets['timer'], 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rx }, { "fillColor": "rgba(151,187,205,0.5)", "strokeColor": "rgba(151,187,205,1)", "pointColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": datasets_tx }, ] } json_net.append({'dev': net['dev'], 'data': network}) cookie_net[net['dev']] = [datasets_rx, datasets_tx] data = json.dumps({'cpu': cpu, 'hdd': json_blk, 'net': json_net}) response.cookies['cpu'] = datasets['cpu'] response.cookies['timer'] = datasets['timer'] response.cookies['hdd'] = cookie_blk response.cookies['net'] = cookie_net response.write(data) except libvirtError: data = json.dumps({'error': 'Error 500'}) response.write(data) return response
def instance(request, host_id, vname): """ Instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) def show_clone_disk(disks): clone_disk = [] for disk in disks: if disk['image'] is None: continue if disk['image'].count(".") and len(disk['image'].rsplit(".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append( {'dev': disk['dev'], 'storage': disk['storage'], 'image': image, 'format': disk['format']}) return clone_disk errors = [] messages = [] time_refresh = TIME_JS_REFRESH * 3 compute = Compute.objects.get(id=host_id) computes = Compute.objects.all() computes_count = len(computes) keymaps = QEMU_KEYMAPS console_types = QEMU_CONSOLE_TYPES try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) conn_interfaces = wvmInterfaces(compute.hostname, compute.login, compute.password, compute.type) ifaces = conn_interfaces.get_ifaces() i = 0 ifaces_all = util.get_free_vfs() ifaces_all = sorted(ifaces_all.iteritems(),key=lambda ax:ax[0]) print ifaces_all temp_ifaces = [] hd_resources = [] hd_resources_checked = conn.get_hd_resources_device() if os.path.exists(util.get_hd_resources_conf()): hd_resources = util.load_hd_resources() for vf_filter in hd_resources.keys(): if vf_filter == "mem" or vf_filter == "vcpu": continue if hd_resources[vf_filter]['used'] == 1: del hd_resources[vf_filter] else: hd_resources = util.create_hd_resources() vcpu_left = hd_resources["vcpu"] mem_left = hd_resources["mem"] del hd_resources["vcpu"] del hd_resources["mem"] is_vf = False status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() hd_resources_checked = conn.get_hd_resources_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() vcpu_max = vcpu_range vcpu_range = xrange(1, int(vcpu_left) + 1) memory_range = [2048, 4096, 6144, 8192, 16384] memory_range = [ memory for memory in memory_range if memory/1024 <= mem_left ] if memory not in memory_range: insort(memory_range, memory) if cur_memory not in memory_range: insort(memory_range, cur_memory) memory_host = conn.get_max_memory() vcpu_host = len(vcpu_max) telnet_port = conn.get_telnet_port() console_type = conn.get_console_type() console_port = conn.get_console_port() console_keymap = conn.get_console_keymap() snapshots = sorted(conn.get_snapshot(), reverse=True) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks) console_passwd = conn.get_console_passwd() vf_infos = util.get_pfvf_map(vname) if not vf_infos: vf_infos = { "test_pf1":[("vf1",'1.0.21'),('vf2','1.0.22')], "test_pf2":[("vf2",'1.0.31'),("vf3",'1.0.32')], "test_pf3":[("vf3",'1.0.41'),("vf5",'1.0.42')], } try: instance = Instance.objects.get(compute_id=host_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=host_id, name=vname, uuid=uuid) instance.save() if request.method == 'POST': if 'start' in request.POST: conn.start() return HttpResponseRedirect(request.get_full_path() + '#shutdown') if 'power' in request.POST: if 'shutdown' == request.POST.get('power', ''): conn.shutdown() return HttpResponseRedirect(request.get_full_path() + '#shutdown') if 'destroy' == request.POST.get('power', ''): conn.force_shutdown() return HttpResponseRedirect(request.get_full_path() + '#forceshutdown') if 'managedsave' == request.POST.get('power', ''): conn.managedsave() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'deletesaveimage' in request.POST: conn.managed_save_remove() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'suspend' in request.POST: conn.suspend() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'resume' in request.POST: conn.resume() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() try: instance = Instance.objects.get(compute_id=host_id, name=vname) instance.delete() conn.delete_disk() hd_resources_all = util.load_hd_resources() for vf in hd_resources_checked: hd_resources_all[vf]['used'] = 0 hd_resources_all["vcpu"] = int(hd_resources_all["vcpu"]) + vcpu hd_resources_all["mem"] = int(hd_resources_all["mem"]) + cur_memory / 1024 util.save_hd_resources(hd_resources_all) finally: conn.delete() return HttpResponseRedirect(reverse('instances', args=[host_id])) if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'umount_iso' in request.POST: image = request.POST.get('path', '') dev = request.POST.get('umount_iso', '') conn.umount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'mount_iso' in request.POST: image = request.POST.get('media', '') dev = request.POST.get('mount_iso', '') conn.mount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'set_autostart' in request.POST: conn.set_autostart(1) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'unset_autostart' in request.POST: conn.set_autostart(0) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_settings' in request.POST: description = request.POST.get('description', '') cur_vcpu_original = vcpu cur_mem_original = cur_memory vcpu = request.POST.get('vcpu', '') cur_vcpu = request.POST.get('cur_vcpu', '') memory = request.POST.get('memory', '') memory_custom = request.POST.get('memory_custom', '') if memory_custom: memory = memory_custom cur_memory = request.POST.get('cur_memory', '') cur_memory_custom = request.POST.get('cur_memory_custom', '') hd_resources_set = request.POST.getlist("ethx") if cur_memory_custom: cur_memory = cur_memory_custom conn.change_settings(description, cur_memory, cur_memory, cur_vcpu, cur_vcpu, hd_resources_set) hd_resources_all = util.load_hd_resources() for vf in hd_resources_checked: if vf not in hd_resources_set: hd_resources_all[vf]['used'] = 0 for vf in hd_resources_set: hd_resources_all[vf]['used'] = 1 hd_resources_all["vcpu"] = int(hd_resources_all["vcpu"]) - int(cur_vcpu) + cur_vcpu_original hd_resources_all["mem"] = (int(hd_resources_all["mem"]) * 1024 - int(cur_memory)) / 1024 + int(cur_mem_original)/1024 util.save_hd_resources(hd_resources_all) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_xml' in request.POST: xml = request.POST.get('inst_xml', '') if xml: conn._defineXML(xml) return HttpResponseRedirect(request.get_full_path() + '#instancexml') if 'set_console_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join([choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('console_passwd', '') clear = request.POST.get('clear_pass', False) if clear: passwd = '' if not passwd and not clear: msg = _("Enter the console password or select Generate") errors.append(msg) if not errors: if not conn.set_console_passwd(passwd): msg = _("Error setting console password. You should check that your instance have an graphic device.") errors.append(msg) else: return HttpResponseRedirect(request.get_full_path() + '#console_pass') if 'set_console_keymap' in request.POST: keymap = request.POST.get('console_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_console_keymap('') else: conn.set_console_keymap(keymap) return HttpResponseRedirect(request.get_full_path() + '#console_keymap') if 'set_console_type' in request.POST: console_type = request.POST.get('console_type', '') conn.set_console_type(console_type) return HttpResponseRedirect(request.get_full_path() + '#console_type') if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') live = request.POST.get('live_migrate', False) unsafe = request.POST.get('unsafe_migrate', False) xml_del = request.POST.get('xml_delete', False) new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname, live, unsafe, xml_del) conn_migrate.define_move(vname) conn_migrate.close() return HttpResponseRedirect(reverse('instance', args=[compute_id, vname])) if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') for post in request.POST: if 'disk' or 'meta' in post: clone_data[post] = request.POST.get(post, '') conn.clone_instance(clone_data) return HttpResponseRedirect(reverse('instance', args=[host_id, clone_data['name']])) if 'add_vf' in request.POST: from django.utils.translation import ugettext as _ count_vf = 0 for pf,vfs in vf_infos.items(): for vf in vfs: count_vf = count_vf+1 cnt_max = settings.vf_cnt_max if count_vf>cnt_max: errors.append(_("One instance has amount max VF is:")+str(cnt_max)) return render_to_response('instance.html', locals(), context_instance=RequestContext(request)) vf_data = request.POST.getlist('interfaces') if (len(vf_data)+count_vf)>cnt_max: errors.append(_("One instance has amount max VF is:")+str(cnt_max)) return render_to_response('instance.html', locals(), context_instance=RequestContext(request)) inst_xml = conn.change_nics_settings(True, vf_data) vf_infos = util.get_pfvf_map(vname) if not vf_infos: vf_infos = { "test_pf1":[("vf1",'1.0.21'),('vf2','1.0.22')], "test_pf2":[("vf2",'1.0.31'),("vf3",'1.0.32')], "test_pf3":[("vf3",'1.0.41'),("vf5",'1.0.42')], } return HttpResponseRedirect('/instance/%s/%s'%(host_id,vname)) if 'del_vf' in request.POST: del_vf_id = request.POST.get('vf_id', '') count_vf = 0 for pf,vfs in vf_infos.items(): for vf in vfs: count_vf = count_vf+1 if count_vf == 1: errors.append(_("It is the last Vf. Can't delete !")) return render_to_response('instance.html', locals(), context_instance=RequestContext(request)) inst_xml = conn.change_nics_settings(False, [del_vf_id]) vf_infos = util.get_pfvf_map(vname) is_vf = True if not vf_infos: vf_infos = { "test_pf1":[("vf1",'1.0.21'),('vf2','1.0.22')], "test_pf2":[("vf2",'1.0.31'),("vf3",'1.0.32')], "test_pf3":[("vf3",'1.0.41'),("vf5",'1.0.42')], } return HttpResponseRedirect('/instance/%s/%s'%(host_id,vname)) conn.close() except libvirtError as err: errors.append(err) return render_to_response('instance.html', locals(), context_instance=RequestContext(request))
def netusage(request, host_id, vname): """ VM net bandwidth """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') datasets_rx = [] datasets_tx = [] json_net = [] cookie_net = {} compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) net_usage = conn.net_usage() conn.close() except libvirtError: net_usage = None try: cookies = request._cookies['net_usage'] except KeyError: cookies = None for net in net_usage: if not cookies: datasets_rx.append(0) datasets_tx.append(0) else: datasets = eval(cookies) datasets_rx = datasets[net['dev']][0] datasets_tx = datasets[net['dev']][1] if len(datasets_rx) > 10: while datasets_rx: del datasets_rx[0] if len(datasets_rx) == 10: break if len(datasets_tx) > 10: while datasets_tx: del datasets_tx[0] if len(datasets_tx) == 10: break if len(datasets_rx) <= 9: datasets_rx.append(int(net['rx']) / 1048576) if len(datasets_rx) == 10: datasets_rx.append(int(net['rx']) / 1048576) del datasets_rx[0] if len(datasets_tx) <= 9: datasets_tx.append(int(net['tx']) / 1048576) if len(datasets_tx) == 10: datasets_tx.append(int(net['tx']) / 1048576) del datasets_tx[0] network = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rx }, { "fillColor": "rgba(151,187,205,0.5)", "strokeColor": "rgba(151,187,205,1)", "pointColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": datasets_tx }, ] } json_net.append({'dev': net['dev'], 'data': network}) cookie_net[net['dev']] = [datasets_rx, datasets_tx] data = simplejson.dumps(json_net) response = HttpResponse() response['Content-Type'] = "text/javascript" response.cookies['net_usage'] = cookie_net response.write(data) return response
def console(request): """ :param request: :return: """ token = '' view_type = '' console_error = None if request.method == 'GET': token = request.GET.get('token', '') view_type = request.GET.get('view', 'lite') try: temptoken = token.split('-', 1) host = int(temptoken[0]) uuid = temptoken[1] instance = Instance.objects.get(compute_id=host, uuid=uuid) conn = wvmInstance(instance.compute.hostname, instance.compute.login, instance.compute.password, instance.compute.type, instance.name) console_type = conn.get_console_type() #console_websocket_port = conn.get_console_websocket_port() console_websocket_port = conn.get_console_port() console_passwd = conn.get_console_passwd() except libvirtError as lib_err: console_type = None console_websocket_port = None console_passwd = None # ws_port = console_websocket_port if console_websocket_port else WS_PORT ws_port = WS_PORT ws_host = WS_PUBLIC_HOST if WS_PUBLIC_HOST else request.get_host() vnc_host = instance.compute.hostname vnc_port = console_websocket_port # if ':' in ws_host: ws_host = re.sub(':[0-9]+', '', ws_host) vnc_token_lines = [] console_page = "console-" + console_type + "-" + view_type + ".html" if console_type == 'vnc': # 设置vnc文件 tools.set_proxy(token, vnc_host, vnc_port) if console_passwd is None: console_passwd = "" #response = render(request, 'console-vnc.html', locals()) vnc_url = reverse('vnc_auto') vnc_url += "?path=websockify/?token=%s&verify=%s" % (token, console_passwd) #_vnc_url = "http://%s:%s/vnc_auto.html?path=websockify/?token=%s&verify=%s" % (ws_host, ws_port, token, console_passwd) #print(_vnc_url) return redirect(vnc_url) elif console_type == 'spice': tools.set_proxy(token, vnc_host, vnc_port) if console_passwd is None: console_passwd = "" response = render(request, console_page, locals()) console_page = "console-" + console_type + "-" + view_type + ".html" if console_type == 'vnc' or console_type == 'spice': response = render(request, console_page, locals()) else: console_error = "Console type: %s no support" % console_type response = render(request, 'console-vnc-lite.html', locals()) response.set_cookie('token', token) return response
def nwfilters(request, compute_id): """ :param request: :return: """ if not request.user.is_superuser: return HttpResponseRedirect(reverse('index')) error_messages = [] nwfilters_all = [] compute = get_object_or_404(Compute, pk=compute_id) try: conn = wvmNWFilters(compute.hostname, compute.login, compute.password, compute.type) if request.method == 'POST': if 'create_nwfilter' in request.POST: xml = request.POST.get('nwfilter_xml', '') if xml: try: util.etree.fromstring(xml) name = util.get_xml_path(xml, '/filter/@name') uuid = util.get_xml_path(xml, '/filter/uuid') except util.etree.ParseError: name = None for nwf in nwfilters: if name == nwf.name(): error_msg = _( "A network filter with this name already exists" ) raise Exception(error_msg) if uuid == nwf.UUIDString(): error_msg = _( "A network filter with this uuid already exists" ) raise Exception(error_msg) else: try: msg = _("Creating NWFilter: %s" % name) conn.create_nwfilter(xml) addlogmsg(request.user.username, compute.hostname, msg) except libvirtError as lib_err: error_messages.append(lib_err.message) addlogmsg(request.user.username, compute.hostname, lib_err.message) if 'del_nwfilter' in request.POST: name = request.POST.get('nwfiltername', '') msg = _("Deleting NWFilter: %s" % name) in_use = False nwfilter = conn.get_nwfilter(name) is_conn = wvmInstances(compute.hostname, compute.login, compute.password, compute.type) instances = is_conn.get_instances() for inst in instances: # if in_use: break i_conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, inst) dom_filterrefs = i_conn.get_filterrefs() if name in dom_filterrefs: in_use = True msg = _( "NWFilter is in use by %s. Cannot be deleted." % inst) error_messages.append(msg) addlogmsg(request.user.username, compute.hostname, msg) i_conn.close() break is_conn.close() if nwfilter and not in_use: nwfilter.undefine() addlogmsg(request.user.username, compute.hostname, msg) if 'cln_nwfilter' in request.POST: name = request.POST.get('nwfiltername', '') cln_name = request.POST.get('cln_name', name + '-clone') conn.clone_nwfilter(name, cln_name) msg = _("Cloning NWFilter %s as %s" % (name, cln_name)) addlogmsg(request.user.username, compute.hostname, msg) for nwf in conn.get_nwfilters(): nwfilters_all.append(conn.get_nwfilter_info(nwf)) conn.close() except libvirtError as lib_err: error_messages.append(lib_err) addlogmsg(request.user.username, compute.hostname, lib_err) except Exception as err: error_messages.append(err) addlogmsg(request.user.username, compute.hostname, err) return render( request, 'nwfilters.html', { 'error_messages': error_messages, 'nwfilters': nwfilters_all, 'compute': compute })
def instusage(request, host_id, vname): """ Return instance usage """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') cookies = {} datasets = {} datasets_rd = [] datasets_wr = [] json_blk = [] cookie_blk = {} blk_error = False datasets_rx = [] datasets_tx = [] json_net = [] cookie_net = {} net_error = False networks = None disks = None compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() if status == 3 or status == 5: networks = conn.get_net_device() disks = conn.get_disk_device() except libvirtError: status = None if status and status == 1: try: blk_usage = conn.disk_usage() cpu_usage = conn.cpu_usage() net_usage = conn.net_usage() conn.close() except libvirtError: blk_usage = None cpu_usage = None net_usage = None try: cookies['cpu'] = request._cookies['cpu'] except KeyError: cookies['cpu'] = None try: cookies['hdd'] = request._cookies['hdd'] except KeyError: cookies['hdd'] = None try: cookies['net'] = request._cookies['net'] except KeyError: cookies['net'] = None if cookies['cpu'] == '{}' or not cookies['cpu'] or not cpu_usage: datasets['cpu'] = [0] else: datasets['cpu'] = eval(cookies['cpu']) if len(datasets['cpu']) > 10: while datasets['cpu']: del datasets['cpu'][0] if len(datasets['cpu']) == 10: break if len(datasets['cpu']) <= 9: datasets['cpu'].append(int(cpu_usage['cpu'])) if len(datasets['cpu']) == 10: datasets['cpu'].append(int(cpu_usage['cpu'])) del datasets['cpu'][0] # Some fix division by 0 Chart.js if len(datasets['cpu']) == 10: if sum(datasets['cpu']) == 0: datasets['cpu'][9] += 0.1 if sum(datasets['cpu']) / 10 == datasets['cpu'][0]: datasets['cpu'][9] += 0.1 cpu = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(241,72,70,0.5)", "strokeColor": "rgba(241,72,70,1)", "pointColor": "rgba(241,72,70,1)", "pointStrokeColor": "#fff", "data": datasets['cpu'] } ] } for blk in blk_usage: if cookies['hdd'] == '{}' or not cookies['hdd'] or not blk_usage: datasets_wr.append(0) datasets_rd.append(0) else: datasets['hdd'] = eval(cookies['hdd']) try: datasets_rd = datasets['hdd'][blk['dev']][0] datasets_wr = datasets['hdd'][blk['dev']][1] except: blk_error = True if not blk_error: if len(datasets_rd) > 10: while datasets_rd: del datasets_rd[0] if len(datasets_rd) == 10: break if len(datasets_wr) > 10: while datasets_wr: del datasets_wr[0] if len(datasets_wr) == 10: break if len(datasets_rd) <= 9: datasets_rd.append(int(blk['rd']) / 1048576) if len(datasets_rd) == 10: datasets_rd.append(int(blk['rd']) / 1048576) del datasets_rd[0] if len(datasets_wr) <= 9: datasets_wr.append(int(blk['wr']) / 1048576) if len(datasets_wr) == 10: datasets_wr.append(int(blk['wr']) / 1048576) del datasets_wr[0] # Some fix division by 0 Chart.js if len(datasets_rd) == 10: if sum(datasets_rd) == 0: datasets_rd[9] += 0.01 if sum(datasets_rd) / 10 == datasets_rd[0]: datasets_rd[9] += 0.01 disk = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rd }, { "fillColor": "rgba(249,134,33,0.5)", "strokeColor": "rgba(249,134,33,1)", "pointColor": "rgba(249,134,33,1)", "pointStrokeColor": "#fff", "data": datasets_wr }, ] } json_blk.append({'dev': blk['dev'], 'data': disk}) cookie_blk[blk['dev']] = [datasets_rd, datasets_wr] for net in net_usage: if cookies['net'] == '{}' or not cookies['net'] or not net_usage: datasets_rx.append(0) datasets_tx.append(0) else: datasets['net'] = eval(cookies['net']) try: datasets_rx = datasets['net'][net['dev']][0] datasets_tx = datasets['net'][net['dev']][1] except: net_error = True if not net_error: if len(datasets_rx) > 10: while datasets_rx: del datasets_rx[0] if len(datasets_rx) == 10: break if len(datasets_tx) > 10: while datasets_tx: del datasets_tx[0] if len(datasets_tx) == 10: break if len(datasets_rx) <= 9: datasets_rx.append(int(net['rx']) / 1048576) if len(datasets_rx) == 10: datasets_rx.append(int(net['rx']) / 1048576) del datasets_rx[0] if len(datasets_tx) <= 9: datasets_tx.append(int(net['tx']) / 1048576) if len(datasets_tx) == 10: datasets_tx.append(int(net['tx']) / 1048576) del datasets_tx[0] # Some fix division by 0 Chart.js if len(datasets_rx) == 10: if sum(datasets_rx) == 0: datasets_rx[9] += 0.01 if sum(datasets_rx) / 10 == datasets_rx[0]: datasets_rx[9] += 0.01 network = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rx }, { "fillColor": "rgba(151,187,205,0.5)", "strokeColor": "rgba(151,187,205,1)", "pointColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": datasets_tx }, ] } json_net.append({'dev': net['dev'], 'data': network}) cookie_net[net['dev']] = [datasets_rx, datasets_tx] data = json.dumps({'status': status, 'cpu': cpu, 'hdd': json_blk, 'net': json_net}) else: datasets = [0] * 10 cpu = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(241,72,70,0.5)", "strokeColor": "rgba(241,72,70,1)", "pointColor": "rgba(241,72,70,1)", "pointStrokeColor": "#fff", "data": datasets } ] } for i, net in enumerate(networks): datasets_rx = [0] * 10 datasets_tx = [0] * 10 network = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rx }, { "fillColor": "rgba(151,187,205,0.5)", "strokeColor": "rgba(151,187,205,1)", "pointColor": "rgba(151,187,205,1)", "pointStrokeColor": "#fff", "data": datasets_tx }, ] } json_net.append({'dev': i, 'data': network}) for blk in disks: datasets_wr = [0] * 10 datasets_rd = [0] * 10 disk = { 'labels': [""] * 10, 'datasets': [ { "fillColor": "rgba(83,191,189,0.5)", "strokeColor": "rgba(83,191,189,1)", "pointColor": "rgba(83,191,189,1)", "pointStrokeColor": "#fff", "data": datasets_rd }, { "fillColor": "rgba(249,134,33,0.5)", "strokeColor": "rgba(249,134,33,1)", "pointColor": "rgba(249,134,33,1)", "pointStrokeColor": "#fff", "data": datasets_wr }, ] } json_blk.append({'dev': blk['dev'], 'data': disk}) data = json.dumps({'status': status, 'cpu': cpu, 'hdd': json_blk, 'net': json_net}) response = HttpResponse() response['Content-Type'] = "text/javascript" if status == 1: response.cookies['cpu'] = datasets['cpu'] response.cookies['hdd'] = cookie_blk response.cookies['net'] = cookie_net response.write(data) return response
def instance(request, host_id, vname): """ Instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') def show_clone_disk(disks): clone_disk = [] for disk in disks: if disk['image'].count(".") and len(disk['image'].rsplit(".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append({'dev': disk['dev'], 'storage': disk['storage'], 'image': image}) return clone_disk errors = [] messages = [] time_refresh = TIME_JS_REFRESH compute = Compute.objects.get(id=host_id) computes = Compute.objects.all() computes_count = len(computes) keymaps = QEMU_KEYMAPS try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 1024, 2048, 4096, 6144, 8192, 16384] memory_host = conn.get_max_memory() vcpu_host = len(vcpu_range) telnet_port = conn.get_telnet_port() vnc_port = conn.get_vnc() vnc_keymap = conn.get_vnc_keymap snapshots = sorted(conn.get_snapshot(), reverse=True) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks) except libvirtError as msg_error: errors.append(msg_error.message) try: instance = Instance.objects.get(compute_id=host_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=host_id, name=vname, uuid=uuid) instance.save() try: if request.method == 'POST': if 'start' in request.POST: conn.start() return HttpResponseRedirect(request.get_full_path()) if 'power' in request.POST: if 'shutdown' == request.POST.get('power', ''): conn.shutdown() return HttpResponseRedirect(request.get_full_path() + '#shutdown') if 'destroy' == request.POST.get('power', ''): conn.force_shutdown() return HttpResponseRedirect(request.get_full_path() + '#forceshutdown') if 'managedsave' == request.POST.get('power', ''): conn.managedsave() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'deletesaveimage' in request.POST: conn.managed_save_remove() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'suspend' in request.POST: conn.suspend() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'resume' in request.POST: conn.resume() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() if request.POST.get('delete_disk', ''): conn.delete_disk() try: instance = Instance.objects.get(compute_id=host_id, name=vname) instance.delete() finally: conn.delete() return HttpResponseRedirect('/instances/%s/' % host_id) if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'umount_iso' in request.POST: image = request.POST.get('path', '') dev = request.POST.get('umount_iso', '') conn.umount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'mount_iso' in request.POST: image = request.POST.get('media', '') dev = request.POST.get('mount_iso', '') conn.mount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'set_autostart' in request.POST: conn.set_autostart(1) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'unset_autostart' in request.POST: conn.set_autostart(0) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_settings' in request.POST: description = request.POST.get('description', '') vcpu = request.POST.get('vcpu', '') cur_vcpu = request.POST.get('cur_vcpu', '') memory = request.POST.get('memory', '') cur_memory = request.POST.get('cur_memory', '') conn.change_settings(description, cur_memory, memory, cur_vcpu, vcpu) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_xml' in request.POST: xml = request.POST.get('inst_xml', '') if xml: conn._defineXML(xml) return HttpResponseRedirect(request.get_full_path() + '#instancexml') if 'set_vnc_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join([choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('vnc_passwd', '') clear = request.POST.get('clear_pass', False) if not passwd and not clear: msg = _("Enter the VNC password or select Generate") errors.append(msg) if not errors: conn.set_vnc_passwd(passwd) return HttpResponseRedirect(request.get_full_path() + '#vnc_pass') if 'set_vnc_keymap' in request.POST: keymap = request.POST.get('vnc_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_vnc_keymap('') else: conn.set_vnc_keymap(keymap) return HttpResponseRedirect(request.get_full_path() + '#vnc_keymap') if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname) conn_migrate.define_move(vname) conn_migrate.close() return HttpResponseRedirect('/instance/%s/%s' % (compute_id, vname)) if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') for post in request.POST: if 'disk' in post: clone_data[post] = request.POST.get(post, '') conn.clone_instance(clone_data) return HttpResponseRedirect('/instance/%s/%s' % (host_id, clone_data['name'])) conn.close() except libvirtError as msg_error: errors.append(msg_error.message) return render_to_response('instance.html', locals(), context_instance=RequestContext(request))
def instance(request, host_id, vname): """ Instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login')) def show_clone_disk(disks): clone_disk = [] for disk in disks: if disk['image'] is None: continue if disk['image'].count(".") and len(disk['image'].rsplit(".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append( {'dev': disk['dev'], 'storage': disk['storage'], 'image': image, 'format': disk['format']}) return clone_disk errors = [] messages = [] time_refresh = TIME_JS_REFRESH * 3 compute = Compute.objects.get(id=host_id) computes = Compute.objects.all() computes_count = len(computes) keymaps = QEMU_KEYMAPS console_types = QEMU_CONSOLE_TYPES try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 768, 1024, 2048, 4096, 6144, 8192, 16384] if memory not in memory_range: insort(memory_range, memory) if cur_memory not in memory_range: insort(memory_range, cur_memory) memory_host = conn.get_max_memory() vcpu_host = len(vcpu_range) telnet_port = conn.get_telnet_port() console_type = conn.get_console_type() console_port = conn.get_console_port() console_keymap = conn.get_console_keymap() snapshots = sorted(conn.get_snapshot(), reverse=True) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks) console_passwd = conn.get_console_passwd() try: instance = Instance.objects.get(compute_id=host_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=host_id, name=vname, uuid=uuid) instance.save() if request.method == 'POST': if 'start' in request.POST: conn.start() return HttpResponseRedirect(request.get_full_path() + '#shutdown') if 'power' in request.POST: if 'shutdown' == request.POST.get('power', ''): conn.shutdown() return HttpResponseRedirect(request.get_full_path() + '#shutdown') if 'destroy' == request.POST.get('power', ''): conn.force_shutdown() return HttpResponseRedirect(request.get_full_path() + '#forceshutdown') if 'managedsave' == request.POST.get('power', ''): conn.managedsave() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'deletesaveimage' in request.POST: conn.managed_save_remove() return HttpResponseRedirect(request.get_full_path() + '#managedsave') if 'suspend' in request.POST: conn.suspend() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'pmwakeup' in request.POST: conn.pMWakeup() return HttpResponseRedirect(request.get_full_path() + '#pmwakeup') if 'resume' in request.POST: conn.resume() return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() try: instance = Instance.objects.get(compute_id=host_id, name=vname) instance.delete() if request.POST.get('delete_disk', ''): conn.delete_disk() finally: conn.delete() return HttpResponseRedirect(reverse('instances', args=[host_id])) if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'umount_iso' in request.POST: image = request.POST.get('path', '') dev = request.POST.get('umount_iso', '') conn.umount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'mount_iso' in request.POST: image = request.POST.get('media', '') dev = request.POST.get('mount_iso', '') conn.mount_iso(dev, image) return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'add_cdrom' in request.POST: conn.add_cdrom() return HttpResponseRedirect(request.get_full_path() + '#instancemedia') if 'set_autostart' in request.POST: conn.set_autostart(1) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'unset_autostart' in request.POST: conn.set_autostart(0) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_settings' in request.POST: description = request.POST.get('description', '') vcpu = request.POST.get('vcpu', '') cur_vcpu = request.POST.get('cur_vcpu', '') memory = request.POST.get('memory', '') memory_custom = request.POST.get('memory_custom', '') if memory_custom: memory = memory_custom cur_memory = request.POST.get('cur_memory', '') cur_memory_custom = request.POST.get('cur_memory_custom', '') if cur_memory_custom: cur_memory = cur_memory_custom conn.change_settings(description, cur_memory, memory, cur_vcpu, vcpu) return HttpResponseRedirect(request.get_full_path() + '#instancesettings') if 'change_xml' in request.POST: xml = request.POST.get('inst_xml', '') if xml: conn._defineXML(xml) return HttpResponseRedirect(request.get_full_path() + '#instancexml') if 'set_console_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join([choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('console_passwd', '') clear = request.POST.get('clear_pass', False) if clear: passwd = '' if not passwd and not clear: msg = _("Enter the console password or select Generate") errors.append(msg) if not errors: if not conn.set_console_passwd(passwd): msg = _("Error setting console password. You should check that your instance have an graphic device.") errors.append(msg) else: return HttpResponseRedirect(request.get_full_path() + '#console_pass') if 'set_console_keymap' in request.POST: keymap = request.POST.get('console_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_console_keymap('') else: conn.set_console_keymap(keymap) return HttpResponseRedirect(request.get_full_path() + '#console_keymap') if 'set_console_type' in request.POST: console_type = request.POST.get('console_type', '') conn.set_console_type(console_type) return HttpResponseRedirect(request.get_full_path() + '#console_type') if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') live = request.POST.get('live_migrate', False) unsafe = request.POST.get('unsafe_migrate', False) xml_del = request.POST.get('xml_delete', False) new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname, live, unsafe, xml_del) conn_migrate.define_move(vname) conn_migrate.close() return HttpResponseRedirect(reverse('instance', args=[compute_id, vname])) if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) return HttpResponseRedirect(request.get_full_path() + '#istaceshapshosts') if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') for post in request.POST: if 'disk' or 'meta' in post: clone_data[post] = request.POST.get(post, '') conn.clone_instance(clone_data) return HttpResponseRedirect(reverse('instance', args=[host_id, clone_data['name']])) conn.close() except libvirtError as err: errors.append(err) return render_to_response('instance.html', locals(), context_instance=RequestContext(request))
def inst_graph(request, compute_id, vname): """ :param request: :return: """ datasets = {} json_blk = [] datasets_blk = {} json_net = [] datasets_net = {} cookies = {} points = 5 curent_time = time.strftime("%H:%M:%S") compute = get_object_or_404(Compute, pk=compute_id) response = HttpResponse() response['Content-Type'] = "text/javascript" def check_points(dataset): if len(dataset) > points: dataset.pop(0) return dataset try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) cpu_usage = conn.cpu_usage() blk_usage = conn.disk_usage() net_usage = conn.net_usage() conn.close() try: cookies['cpu'] = request.COOKIES['cpu'] cookies['blk'] = request.COOKIES['blk'] cookies['net'] = request.COOKIES['net'] cookies['timer'] = request.COOKIES['timer'] except KeyError: cookies['cpu'] = None cookies['blk'] = None cookies['net'] = None if not cookies['cpu']: datasets['cpu'] = [0] * points datasets['timer'] = [0] * points else: datasets['cpu'] = eval(cookies['cpu']) datasets['timer'] = eval(cookies['timer']) datasets['timer'].append(curent_time) datasets['cpu'].append(int(cpu_usage['cpu'])) datasets['timer'] = check_points(datasets['timer']) datasets['cpu'] = check_points(datasets['cpu']) for blk in blk_usage: if not cookies['blk']: datasets_wr = [0] * points datasets_rd = [0] * points else: datasets['blk'] = eval(cookies['blk']) datasets_rd = datasets['blk'][blk['dev']][0] datasets_wr = datasets['blk'][blk['dev']][1] datasets_rd.append(int(blk['rd']) / 1048576) datasets_wr.append(int(blk['wr']) / 1048576) datasets_rd = check_points(datasets_rd) datasets_wr = check_points(datasets_wr) json_blk.append({ 'dev': blk['dev'], 'data': [datasets_rd, datasets_wr] }) datasets_blk[blk['dev']] = [datasets_rd, datasets_wr] for net in net_usage: if not cookies['net']: datasets_rx = [0] * points datasets_tx = [0] * points else: datasets['net'] = eval(cookies['net']) datasets_rx = datasets['net'][net['dev']][0] datasets_tx = datasets['net'][net['dev']][1] datasets_rx.append(int(net['rx']) / 1048576) datasets_tx.append(int(net['tx']) / 1048576) datasets_rx = check_points(datasets_rx) datasets_tx = check_points(datasets_tx) json_net.append({ 'dev': net['dev'], 'data': [datasets_rx, datasets_tx] }) datasets_net[net['dev']] = [datasets_rx, datasets_tx] data = json.dumps({ 'cpudata': datasets['cpu'], 'blkdata': json_blk, 'netdata': json_net, 'timeline': datasets['timer'] }) response.cookies['cpu'] = datasets['cpu'] response.cookies['timer'] = datasets['timer'] response.cookies['blk'] = datasets_blk response.cookies['net'] = datasets_net except libvirtError: data = json.dumps({'error': 'Error 500'}) response.write(data) return response
def instance(request, compute_id, vname): """ :param request: :return: """ error_messages = [] messages = [] compute = get_object_or_404(Compute, pk=compute_id) computes = Compute.objects.all() computes_count = len(computes) publickeys = UserSSHKey.objects.filter(user_id=request.user.id) keymaps = QEMU_KEYMAPS console_types = QEMU_CONSOLE_TYPES try: userinstace = UserInstance.objects.get(instance__compute_id=compute_id, instance__name=vname, user__id=request.user.id) except UserInstance.DoesNotExist: userinstace = None if not request.user.is_superuser: if not userinstace: return HttpResponseRedirect(reverse('index')) def show_clone_disk(disks, vname=''): clone_disk = [] for disk in disks: if disk['image'] is None: continue if disk['image'].count("-") and disk['image'].rsplit("-", 1)[0] == vname: name, suffix = disk['image'].rsplit("-", 1) image = name + "-clone" + "-" + suffix elif disk['image'].count(".") and len(disk['image'].rsplit(".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append( {'dev': disk['dev'], 'storage': disk['storage'], 'image': image, 'format': disk['format']}) return clone_disk def filesizefstr(size_str): if size_str == '': return 0 size_str = size_str.encode('ascii', 'ignore').upper().translate(None, " B") if 'K' == size_str[-1]: return long(float(size_str[:-1]))<<10 elif 'M' == size_str[-1]: return long(float(size_str[:-1]))<<20 elif 'G' == size_str[-1]: return long(float(size_str[:-1]))<<30 elif 'T' == size_str[-1]: return long(float(size_str[:-1]))<<40 elif 'P' == size_str[-1]: return long(float(size_str[:-1]))<<50 else: return long(float(size_str)) def get_clone_free_names(size=10): prefix = settings.CLONE_INSTANCE_DEFAULT_PREFIX free_names = [] existing_names = [i.name for i in Instance.objects.filter(name__startswith=prefix)] index = 1 while len(free_names) < size: new_name = prefix + str(index) if new_name not in existing_names: free_names.append(new_name) index += 1 return free_names def check_user_quota(instance, cpu, memory, disk_size): user_instances = UserInstance.objects.filter(user_id=request.user.id, instance__is_template=False) instance += len(user_instances) for usr_inst in user_instances: if connection_manager.host_is_up(usr_inst.instance.compute.type, usr_inst.instance.compute.hostname): conn = wvmInstance(usr_inst.instance.compute, usr_inst.instance.compute.login, usr_inst.instance.compute.password, usr_inst.instance.compute.type, usr_inst.instance.name) cpu += int(conn.get_vcpu()) memory += int(conn.get_memory()) for disk in conn.get_disk_device(): disk_size += int(disk['size'])>>30 ua = request.user.userattributes msg = "" if ua.max_instances > 0 and instance > ua.max_instances: msg = "instance" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (instance, ua.max_instances) if ua.max_cpus > 0 and cpu > ua.max_cpus: msg = "cpu" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (cpu, ua.max_cpus) if ua.max_memory > 0 and memory > ua.max_memory: msg = "memory" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (memory, ua.max_memory) if ua.max_disk_size > 0 and disk_size > ua.max_disk_size: msg = "disk" if settings.QUOTA_DEBUG: msg += " (%s > %s)" % (disk_size, ua.max_disk_size) return msg try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() title = conn.get_title() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 768, 1024, 2048, 4096, 6144, 8192, 16384] if memory not in memory_range: insort(memory_range, memory) if cur_memory not in memory_range: insort(memory_range, cur_memory) memory_host = conn.get_max_memory() vcpu_host = len(vcpu_range) telnet_port = conn.get_telnet_port() console_type = conn.get_console_type() console_port = conn.get_console_port() console_keymap = conn.get_console_keymap() snapshots = sorted(conn.get_snapshot(), reverse=True) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks, vname) console_passwd = conn.get_console_passwd() clone_free_names = get_clone_free_names() user_quota_msg = check_user_quota(0, 0, 0, 0) try: instance = Instance.objects.get(compute_id=compute_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=compute_id, name=vname, uuid=uuid) instance.save() if request.method == 'POST': if 'poweron' in request.POST: conn.start() msg = _("Power On") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#poweron') if 'powercycle' in request.POST: conn.force_shutdown() conn.start() msg = _("Power Cycle") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#powercycle') if 'poweroff' in request.POST: conn.shutdown() msg = _("Power Off") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#poweroff') if 'powerforce' in request.POST: conn.force_shutdown() msg = _("Force Off") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#powerforce') if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() if request.POST.get('delete_disk', ''): conn.delete_disk() conn.delete() instance = Instance.objects.get(compute_id=compute_id, name=vname) instance_name = instance.name instance.delete() try: del_userinstance = UserInstance.objects.filter(instance__compute_id=compute_id, instance__name=vname) del_userinstance.delete() except UserInstance.DoesNotExist: pass msg = _("Destroy") addlogmsg(request.user.username, instance_name, msg) return HttpResponseRedirect(reverse('instances')) if 'rootpasswd' in request.POST: passwd = request.POST.get('passwd', '') passwd_hash = crypt.crypt(passwd, '$6$kgPoiREy') data = {'action': 'password', 'passwd': passwd_hash, 'vname': vname} if conn.get_status() == 5: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((compute.hostname, 16510)) s.send(json.dumps(data)) result = json.loads(s.recv(1024)) s.close() msg = _("Reset root password") addlogmsg(request.user.username, instance.name, msg) if result['return'] == 'success': messages.append(msg) else: error_messages.append(msg) else: msg = _("Please shutdow down your instance and then try again") error_messages.append(msg) if 'addpublickey' in request.POST: sshkeyid = request.POST.get('sshkeyid', '') publickey = UserSSHKey.objects.get(id=sshkeyid) data = {'action': 'publickey', 'key': publickey.keypublic, 'vname': vname} if conn.get_status() == 5: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((compute.hostname, 16510)) s.send(json.dumps(data)) result = json.loads(s.recv(1024)) s.close() msg = _("Installed new ssh public key %s" % publickey.keyname) addlogmsg(request.user.username, instance.name, msg) if result['return'] == 'success': messages.append(msg) else: error_messages.append(msg) else: msg = _("Please shutdow down your instance and then try again") error_messages.append(msg) if 'resize' in request.POST: new_vcpu = request.POST.get('vcpu', '') new_cur_vcpu = request.POST.get('cur_vcpu', '') new_memory = request.POST.get('memory', '') new_memory_custom = request.POST.get('memory_custom', '') if new_memory_custom: new_memory = new_memory_custom new_cur_memory = request.POST.get('cur_memory', '') new_cur_memory_custom = request.POST.get('cur_memory_custom', '') if new_cur_memory_custom: new_cur_memory = new_cur_memory_custom disks_new = [] for disk in disks: input_disk_size = filesizefstr(request.POST.get('disk_size_' + disk['dev'], '')) if input_disk_size > disk['size']+(64<<20): disk['size_new'] = input_disk_size disks_new.append(disk) disk_sum = sum([disk['size']>>30 for disk in disks_new]) disk_new_sum = sum([disk['size_new']>>30 for disk in disks_new]) quota_msg = check_user_quota(0, int(new_vcpu)-vcpu, int(new_memory)-memory, disk_new_sum-disk_sum) if not request.user.is_superuser and quota_msg: msg = _("User %s quota reached, cannot resize '%s'!" % (quota_msg, instance.name)) error_messages.append(msg) else: cur_memory = new_cur_memory memory = new_memory cur_vcpu = new_cur_vcpu vcpu = new_vcpu conn.resize(cur_memory, memory, cur_vcpu, vcpu, disks_new) msg = _("Resize") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#resize') if 'umount_iso' in request.POST: image = request.POST.get('path', '') dev = request.POST.get('umount_iso', '') conn.umount_iso(dev, image) msg = _("Mount media") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#media') if 'mount_iso' in request.POST: image = request.POST.get('media', '') dev = request.POST.get('mount_iso', '') conn.mount_iso(dev, image) msg = _("Umount media") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#media') if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) msg = _("New snapshot") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#restoresnapshot') if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) msg = _("Delete snapshot") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#restoresnapshot') if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) msg = _("Revert snapshot") addlogmsg(request.user.username, instance.name, msg) if request.user.is_superuser: if 'suspend' in request.POST: conn.suspend() msg = _("Suspend") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#resume') if 'resume' in request.POST: conn.resume() msg = _("Resume") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#suspend') if 'set_autostart' in request.POST: conn.set_autostart(1) msg = _("Set autostart") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#autostart') if 'unset_autostart' in request.POST: conn.set_autostart(0) msg = _("Unset autostart") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#autostart') if 'change_xml' in request.POST: exit_xml = request.POST.get('inst_xml', '') if exit_xml: conn._defineXML(exit_xml) msg = _("Edit XML") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#xmledit') if 'set_console_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join([choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('console_passwd', '') clear = request.POST.get('clear_pass', False) if clear: passwd = '' if not passwd and not clear: msg = _("Enter the console password or select Generate") error_messages.append(msg) if not error_messages: if not conn.set_console_passwd(passwd): msg = _("Error setting console password. You should check that your instance have an graphic device.") error_messages.append(msg) else: msg = _("Set VNC password") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if 'set_console_keymap' in request.POST: keymap = request.POST.get('console_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_console_keymap('') else: conn.set_console_keymap(keymap) msg = _("Set VNC keymap") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if 'set_console_type' in request.POST: console_type = request.POST.get('console_type', '') conn.set_console_type(console_type) msg = _("Set VNC type") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#vncsettings') if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') live = request.POST.get('live_migrate', False) unsafe = request.POST.get('unsafe_migrate', False) xml_del = request.POST.get('xml_delete', False) new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname, live, unsafe, xml_del) conn_migrate.define_move(vname) conn_migrate.close() msg = _("Migrate") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(reverse('instance', args=[compute_id, vname])) if 'change_network' in request.POST: network_data = {} for post in request.POST: if post.startswith('net-'): network_data[post] = request.POST.get(post, '') conn.change_network(network_data) msg = _("Edit network") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#network') if 'change_options' in request.POST: instance.is_template = request.POST.get('is_template', False) instance.save() options = {} for post in request.POST: if post in ['title', 'description']: options[post] = request.POST.get(post, '') conn.set_options(options) msg = _("Edit options") addlogmsg(request.user.username, instance.name, msg) return HttpResponseRedirect(request.get_full_path() + '#options') if request.user.is_superuser or request.user.userattributes.can_clone_instances: if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') disk_sum = sum([disk['size']>>30 for disk in disks]) quota_msg = check_user_quota(1, vcpu, memory, disk_sum) check_instance = Instance.objects.filter(name=clone_data['name']) if not request.user.is_superuser and quota_msg: msg = _("User %s quota reached, cannot create '%s'!" % (quota_msg, clone_data['name'])) error_messages.append(msg) elif check_instance: msg = _("Instance '%s' already exists!" % clone_data['name']) error_messages.append(msg) else: for post in request.POST: clone_data[post] = request.POST.get(post, '') new_uuid = conn.clone_instance(clone_data) new_instance = Instance(compute_id=compute_id, name=clone_data['name'], uuid=new_uuid) new_instance.save() userinstance = UserInstance(instance_id=new_instance.id, user_id=request.user.id, is_delete=True) userinstance.save() msg = _("Clone of '%s'" % instance.name) addlogmsg(request.user.username, new_instance.name, msg) return HttpResponseRedirect(reverse('instance', args=[compute_id, clone_data['name']])) conn.close() except libvirtError as lib_err: error_messages.append(lib_err.message) addlogmsg(request.user.username, vname, lib_err.message) return render(request, 'instance.html', locals())
def instance(request, host_id, vname): """ Instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') def show_clone_disk(disks): clone_disk = [] for disk in disks: if disk['image'].count(".") and len(disk['image'].rsplit(".", 1)[1]) <= 7: name, suffix = disk['image'].rsplit(".", 1) image = name + "-clone" + "." + suffix else: image = disk['image'] + "-clone" clone_disk.append({'dev': disk['dev'], 'storage': disk['storage'], 'image': image}) return clone_disk errors = [] messages = [] time_refresh = TIME_JS_REFRESH compute = Compute.objects.get(id=host_id) computes = Compute.objects.all() computes_count = len(computes) keymaps = QEMU_KEYMAPS try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() cur_vcpu = conn.get_cur_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() cur_memory = conn.get_cur_memory() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 1024, 2048, 4096, 6144, 8192, 16384] memory_host = conn.get_max_memory() vcpu_host = len(vcpu_range) telnet_port = conn.get_telnet_port() vnc_port = conn.get_vnc() vnc_keymap = conn.get_vnc_keymap snapshots = sorted(conn.get_snapshot(), reverse=True) inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) has_managed_save_image = conn.get_managed_save_image() clone_disks = show_clone_disk(disks) except libvirtError as msg_error: errors.append(msg_error.message) try: instance = Instance.objects.get(compute_id=host_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=host_id, name=vname, uuid=uuid) instance.save() try: if request.method == 'POST': if 'start' in request.POST: conn.start() return HttpResponseRedirect(request.get_full_path()) if 'power' in request.POST: if 'shutdown' == request.POST.get('power', ''): conn.shutdown() return HttpResponseRedirect(request.get_full_path()) if 'destroy' == request.POST.get('power', ''): conn.force_shutdown() return HttpResponseRedirect(request.get_full_path()) if 'managedsave' == request.POST.get('power', ''): conn.managedsave() return HttpResponseRedirect(request.get_full_path()) if 'deletesaveimage' in request.POST: conn.managed_save_remove() return HttpResponseRedirect(request.get_full_path()) if 'suspend' in request.POST: conn.suspend() return HttpResponseRedirect(request.get_full_path()) if 'resume' in request.POST: conn.resume() return HttpResponseRedirect(request.get_full_path()) if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() if request.POST.get('delete_disk', ''): conn.delete_disk() try: instance = Instance.objects.get(compute_id=host_id, name=vname) instance.delete() finally: conn.delete() return HttpResponseRedirect('/instances/%s/' % host_id) if 'snapshot' in request.POST: name = request.POST.get('name', '') conn.create_snapshot(name) msg = _("Snapshot '%s' has been created successful" % name) messages.append(msg) if 'umount_iso' in request.POST: image = request.POST.get('path', '') dev = request.POST.get('umount_iso', '') conn.umount_iso(dev, image) return HttpResponseRedirect(request.get_full_path()) if 'mount_iso' in request.POST: image = request.POST.get('media', '') dev = request.POST.get('mount_iso', '') conn.mount_iso(dev, image) return HttpResponseRedirect(request.get_full_path()) if 'set_autostart' in request.POST: conn.set_autostart(1) return HttpResponseRedirect(request.get_full_path()) if 'unset_autostart' in request.POST: conn.set_autostart(0) return HttpResponseRedirect(request.get_full_path()) if 'change_settings' in request.POST: description = request.POST.get('description', '') vcpu = request.POST.get('vcpu', '') cur_vcpu = request.POST.get('cur_vcpu', '') memory = request.POST.get('memory', '') cur_memory = request.POST.get('cur_memory', '') conn.change_settings(description, cur_memory, memory, cur_vcpu, vcpu) return HttpResponseRedirect(request.get_full_path()) if 'change_xml' in request.POST: xml = request.POST.get('inst_xml', '') if xml: conn._defineXML(xml) return HttpResponseRedirect(request.get_full_path()) if 'set_vnc_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join([choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('vnc_passwd', '') clear = request.POST.get('clear_pass', False) if not passwd and not clear: msg = _("Enter the VNC password or select Generate") errors.append(msg) if not errors: conn.set_vnc_passwd(passwd) return HttpResponseRedirect(request.get_full_path()) if 'set_vnc_keymap' in request.POST: keymap = request.POST.get('vnc_keymap', '') clear = request.POST.get('clear_keymap', False) if clear: conn.set_vnc_keymap('') else: conn.set_vnc_keymap(keymap) return HttpResponseRedirect(request.get_full_path()) if 'migrate' in request.POST: compute_id = request.POST.get('compute_id', '') new_compute = Compute.objects.get(id=compute_id) conn_migrate = wvmInstances(new_compute.hostname, new_compute.login, new_compute.password, new_compute.type) conn_migrate.moveto(conn, vname) conn_migrate.define_move(vname) conn_migrate.close() return HttpResponseRedirect('/instance/%s/%s' % (compute_id, vname)) if 'delete_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_delete(snap_name) return HttpResponseRedirect(request.get_full_path()) if 'revert_snapshot' in request.POST: snap_name = request.POST.get('name', '') conn.snapshot_revert(snap_name) msg = _("Successful revert snapshot: ") msg += snap_name messages.append(msg) if 'clone' in request.POST: clone_data = {} clone_data['name'] = request.POST.get('name', '') for post in request.POST: if 'disk' in post: clone_data[post] = request.POST.get(post, '') conn.clone_instance(clone_data) return HttpResponseRedirect('/instance/%s/%s' % (host_id, clone_data['name'])) conn.close() except libvirtError as msg_error: errors.append(msg_error.message) return render_to_response('instance.html', locals(), context_instance=RequestContext(request))
def instance(request, host_id, vname): """ Instance block """ if not request.user.is_authenticated(): return HttpResponseRedirect('/login') errors = [] messages = [] time_refresh = TIME_JS_REFRESH compute = Compute.objects.get(id=host_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) status = conn.get_status() autostart = conn.get_autostart() vcpu = conn.get_vcpu() uuid = conn.get_uuid() memory = conn.get_memory() description = conn.get_description() disks = conn.get_disk_device() media = conn.get_media_device() networks = conn.get_net_device() media_iso = sorted(conn.get_iso_media()) vcpu_range = conn.get_max_cpus() memory_range = [256, 512, 1024, 2048, 4096, 8192, 16384] vnc_port = conn.get_vnc() inst_xml = conn._XMLDesc(VIR_DOMAIN_XML_SECURE) except libvirtError as msg_error: errors.append(msg_error.message) try: instance = Instance.objects.get(compute_id=host_id, name=vname) if instance.uuid != uuid: instance.uuid = uuid instance.save() except Instance.DoesNotExist: instance = Instance(compute_id=host_id, name=vname, uuid=uuid) instance.save() try: if request.method == 'POST': if 'start' in request.POST: conn.start() return HttpResponseRedirect(request.get_full_path()) if 'power' in request.POST: if 'shutdown' == request.POST.get('power', ''): conn.shutdown() return HttpResponseRedirect(request.get_full_path()) if 'destroy' == request.POST.get('power', ''): conn.force_shutdown() return HttpResponseRedirect(request.get_full_path()) if 'suspend' in request.POST: conn.suspend() return HttpResponseRedirect(request.get_full_path()) if 'resume' in request.POST: conn.resume() return HttpResponseRedirect(request.get_full_path()) if 'delete' in request.POST: if conn.get_status() == 1: conn.force_shutdown() if request.POST.get('delete_disk', ''): conn.delete_disk() try: instance = Instance.objects.get(compute_id=host_id, name=vname) instance.delete() finally: conn.delete() return HttpResponseRedirect('/instances/%s/' % host_id) if 'snapshot' in request.POST: conn.create_snapshot() msg = _("Create snapshot for instance successful") messages.append(msg) if 'umount_iso' in request.POST: image = request.POST.get('iso_media', '') conn.umount_iso(image) return HttpResponseRedirect(request.get_full_path()) if 'mount_iso' in request.POST: image = request.POST.get('iso_media', '') conn.mount_iso(image) return HttpResponseRedirect(request.get_full_path()) if 'set_autostart' in request.POST: conn.set_autostart(1) return HttpResponseRedirect(request.get_full_path()) if 'unset_autostart' in request.POST: conn.set_autostart(0) return HttpResponseRedirect(request.get_full_path()) if 'change_settings' in request.POST: description = request.POST.get('description', '') vcpu = request.POST.get('vcpu', '') memory = request.POST.get('memory', '') conn.change_settings(description, memory, vcpu) return HttpResponseRedirect(request.get_full_path()) if 'change_xml' in request.POST: xml = request.POST.get('inst_xml', '') if xml: conn._defineXML(xml) return HttpResponseRedirect(request.get_full_path()) if 'set_vnc_passwd' in request.POST: if request.POST.get('auto_pass', ''): passwd = ''.join([choice(letters + digits) for i in xrange(12)]) else: passwd = request.POST.get('vnc_passwd', '') if not passwd: msg = _("Enter the VNC password or select Generate") errors.append(msg) if not errors: conn.set_vnc_passwd(passwd) return HttpResponseRedirect(request.get_full_path()) conn.close() except libvirtError as msg_error: errors.append(msg_error.message) return render_to_response('instance.html', locals(), context_instance=RequestContext(request))