Beispiel #1
0
def infrastructure(request):
    """
    Infrastructure page.
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))

    if not request.user.is_staff:
        raise PermissionDenied

    compute = Compute.objects.filter()
    hosts_vms = {}

    for host in compute:
        status = connection_manager.host_is_up(host.type, host.hostname)
        if status:
            try:
                conn = wvmHostDetails(host, host.login, host.password,
                                      host.type, host.hypervisor)
                host_info = conn.get_node_info()
                host_mem = conn.get_memory_usage()
                hosts_vms[host.id, host.name, status, host_info[3], host_info[2],
                          host_mem['percent']] = conn.get_host_instances()
                conn.close()
            except libvirtError:
                hosts_vms[host.id, host.name, status, 0, 0, 0] = None
        else:
            hosts_vms[host.id, host.name, 2, 0, 0, 0] = None

    return render_to_response('infrastructure.html', locals(), context_instance=RequestContext(request))
Beispiel #2
0
 def get_hosts_status(computes):
     """
     Function return all hosts all vds on host
     """
     compute_data = []
     for compute in computes:
         compute_data.append({
             'id':
             compute.id,
             'name':
             compute.name,
             'hostname':
             compute.hostname,
             'status':
             connection_manager.host_is_up(compute.type, compute.hostname),
             'type':
             compute.type,
             'login':
             compute.login,
             'password':
             compute.password,
             'details':
             compute.details
         })
     return compute_data
Beispiel #3
0
def dashboard(request):
    if not request.user.is_authenticated():
        return redirect('login')

    compute = Compute.objects.filter()
    hosts_vms = {}

    for host in compute:
        status = connection_manager.host_is_up(host.type, host.hostname)
        if status:
            try:
                conn = wvmHostDetails(host, host.login, host.password,
                                      host.type)
                host_info = conn.get_node_info()
                host_mem = conn.get_memory_usage()
                hosts_vms[host.id, host.name, status, host_info[3],
                          host_info[2],
                          host_mem['percent']] = conn.get_host_instances()
                conn.close()
            except libvirtError:
                hosts_vms[host.id, host.name, status, 0, 0, 0] = None
        else:
            hosts_vms[host.id, host.name, 2, 0, 0, 0] = None

    return render(request, 'dashboard.html', locals())
Beispiel #4
0
 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
Beispiel #5
0
def infrastructure(request):
    """
    Infrastructure page.
    """
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/login')

    compute = Compute.objects.filter()
    hosts_vms = {}

    for host in compute:
        status = connection_manager.host_is_up(host.type, host.hostname)
        if status:
            try:
                conn = wvmHostDetails(host, host.login, host.password,
                                      host.type)
                host_info = conn.get_node_info()
                host_mem = conn.get_memory_usage()
                hosts_vms[host.id, host.name, status, host_info[3],
                          host_info[2],
                          host_mem['percent']] = conn.get_host_instances()
                conn.close()
            except libvirtError:
                hosts_vms[host.id, host.name, status, 0, 0, 0] = None
        else:
            hosts_vms[host.id, host.name, 2, 0, 0, 0] = None

    return render_to_response('infrastructure.html',
                              locals(),
                              context_instance=RequestContext(request))
Beispiel #6
0
def overview(request, compute_id):
    """
    :param request:
    :param compute_id:
    :return:
    """

    error_messages = []
    compute = get_object_or_404(Compute, pk=compute_id)
    status = 'true' if connection_manager.host_is_up(
        compute.type, compute.hostname) is True else 'false'

    try:
        conn = wvmHostDetails(
            compute.hostname,
            compute.login,
            compute.password,
            compute.type,
        )
        hostname, host_arch, host_memory, logical_cpu, model_cpu, uri_conn = conn.get_node_info(
        )
        hypervisor = conn.get_hypervisors_domain_types()
        mem_usage = conn.get_memory_usage()
        emulator = conn.get_emulator(host_arch)
        version = conn.get_version()
        lib_version = conn.get_lib_version()
        conn.close()
    except libvirtError as lib_err:
        error_messages.append(lib_err)

    return render(request, 'overview.html', locals())
Beispiel #7
0
 def get_hosts_status(hosts):
     """
     Function return all hosts all vds on host
     """
     all_hosts = []
     for host in hosts:
         all_hosts.append({
             'id':
             host.id,
             'name':
             host.name,
             'hostname':
             host.hostname,
             'hypervisor':
             host.hypervisor,
             'status':
             connection_manager.host_is_up(host.type, host.hostname),
             'type':
             host.type,
             'login':
             host.login,
             'password':
             host.password
         })
     return all_hosts
Beispiel #8
0
    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
Beispiel #9
0
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()
Beispiel #10
0
 def get_hosts_status(computes):
     """
     Function return all hosts all vds on host
     """
     compute_data = []
     for compute in computes:
         compute_data.append({'id': compute.id,
                              'name': compute.name,
                              'hostname': compute.hostname,
                              'status': connection_manager.host_is_up(compute.type, compute.hostname),
                              'type': compute.type,
                              'login': compute.login,
                              'password': compute.password
                              })
     return compute_data
Beispiel #11
0
 def get_hosts_status(hosts):
     """
     Function return all hosts all vds on host
     """
     all_hosts = []
     for host in hosts:
         all_hosts.append({'id': host.id,
                           'name': host.name,
                           'hostname': host.hostname,
                           'status': connection_manager.host_is_up(host.type, host.hostname),
                           'type': host.type,
                           'login': host.login,
                           'password': host.password
                           })
     return all_hosts
Beispiel #12
0
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")
Beispiel #13
0
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
Beispiel #14
0
def get_user_instances(user):
    all_user_vms = {}
    user_instances = UserInstance.objects.filter(user=user)
    for usr_inst in user_instances:
        if connection_manager.host_is_up(usr_inst.instance.compute.type,
                                         usr_inst.instance.compute.hostname):
            conn = wvmHostDetails(
                usr_inst.instance.compute.hostname,
                usr_inst.instance.compute.login,
                usr_inst.instance.compute.password,
                usr_inst.instance.compute.type,
            )
            all_user_vms[usr_inst] = conn.get_user_instances(
                usr_inst.instance.name)
            all_user_vms[usr_inst].update(
                {'compute_id': usr_inst.instance.compute.id})
    return all_user_vms
Beispiel #15
0
    def get_hosts_status(hosts):
        """
        Function return all hosts all vds on host
        """
        all_hosts = []
        for host in hosts:
            if (connection_manager.host_is_up(host.hostname, host.login, host.password, host.type)):
                status = 1
            else:
                status = 'Unknown Error'

            all_hosts.append({'id': host.id,
                              'name': host.name,
                              'hostname': host.hostname,
                              'status': status,
                              'type': host.type,
                              'login': host.login,
                              'password': host.password
                              })
        return all_hosts
Beispiel #16
0
def overview(request, compute_id):
    compute = get_object_or_404(Compute, pk=compute_id)
    status = ("true" if connection_manager.host_is_up(
        compute.type, compute.hostname) is True else "false")

    conn = wvmHostDetails(
        compute.hostname,
        compute.login,
        compute.password,
        compute.type,
    )
    hostname, host_arch, host_memory, logical_cpu, model_cpu, uri_conn = conn.get_node_info(
    )
    hypervisor = conn.get_hypervisors_domain_types()
    mem_usage = conn.get_memory_usage()
    emulator = conn.get_emulator(host_arch)
    version = conn.get_version()
    lib_version = conn.get_lib_version()
    conn.close()

    return render(request, "overview.html", locals())
Beispiel #17
0
    def get_hosts_status(hosts):
        """
        Function return all hosts all vds on host
        """
        all_hosts = []
        for host in hosts:
            if (connection_manager.host_is_up(host.hostname, host.login,
                                              host.password, host.type)):
                status = 1
            else:
                status = 'Unknown Error'

            all_hosts.append({
                'id': host.id,
                'name': host.name,
                'hostname': host.hostname,
                'status': status,
                'type': host.type,
                'login': host.login,
                'password': host.password
            })
        return all_hosts
Beispiel #18
0
def infrastructure(request):
    """
    Infrastructure page.
    """
    compute = Compute.objects.filter()
    hosts_vms = {}

    for host in compute:
        if connection_manager.host_is_up(host.hostname, host.login, host.password, host.type):
            try:
                conn = wvmHostDetails(host, host.login, host.password, host.type)
                host_info = conn.get_node_info()
                host_mem = conn.get_memory_usage()
                hosts_vms[host.id, host.name, 1, host_info[3], host_info[2],
                          host_mem['percent']] = conn.get_host_instances()
                conn.close()
            except libvirtError:
                hosts_vms[host.id, host.name, 3, 0, 0, 0] = None
        else:
            hosts_vms[host.id, host.name, 2, 0, 0, 0] = None

    return render(None, 'infrastructure.html', locals(), request)
Beispiel #19
0
def infrastructure(request):
    """
    Infrastructure page.
    """
    compute = Compute.objects.filter()
    hosts_vms = {}

    for host in compute:
        if connection_manager.host_is_up(host.hostname, host.login,
                                         host.password, host.type):
            try:
                conn = wvmHostDetails(host, host.login, host.password,
                                      host.type)
                host_info = conn.get_node_info()
                host_mem = conn.get_memory_usage()
                hosts_vms[host.id, host.name, 1, host_info[3], host_info[2],
                          host_mem['percent']] = conn.get_host_instances()
                conn.close()
            except libvirtError:
                hosts_vms[host.id, host.name, 3, 0, 0, 0] = None
        else:
            hosts_vms[host.id, host.name, 2, 0, 0, 0] = None

    return render(None, 'infrastructure.html', locals(), request)
Beispiel #20
0
 def status(self):
     return connection_manager.host_is_up(self.type, self.hostname)
Beispiel #21
0
def instances(request):
    """
    :param request:
    :return:
    """

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

    error_messages = []
    all_host_vms = {}
    all_user_vms = {}
    computes = Compute.objects.all()

    if not request.user.is_superuser:
        user_instances = UserInstance.objects.filter(user_id=request.user.id)
        for usr_inst in user_instances:
            if connection_manager.host_is_up(usr_inst.instance.compute.type,
                                             usr_inst.instance.compute.hostname):
                conn = wvmHostDetails(usr_inst.instance.compute,
                                      usr_inst.instance.compute.login,
                                      usr_inst.instance.compute.password,
                                      usr_inst.instance.compute.type)
                all_user_vms[usr_inst] = conn.get_user_instances(usr_inst.instance.name)
                all_user_vms[usr_inst].update({'compute_id': usr_inst.instance.compute.id})
    else:
        for comp in computes:
            if connection_manager.host_is_up(comp.type, comp.hostname):
                try:
                    conn = wvmHostDetails(comp, comp.login, comp.password, comp.type)
                    if conn.get_host_instances():
                        all_host_vms[comp.id, comp.name] = conn.get_host_instances()
                        for vm, info in conn.get_host_instances().items():
                            try:
                                check_uuid = Instance.objects.get(compute_id=comp.id, name=vm)
                                if check_uuid.uuid != info['uuid']:
                                    check_uuid.save()
                            except Instance.DoesNotExist:
                                check_uuid = Instance(compute_id=comp.id, name=vm, uuid=info['uuid'])
                                check_uuid.save()
                    conn.close()
                except libvirtError as lib_err:
                    error_messages.append(lib_err)

    if request.method == 'POST':
        name = request.POST.get('name', '')
        compute_id = request.POST.get('compute_id', '')
        instance = Instance.objects.get(compute_id=compute_id, name=name)
        try:
            conn = wvmInstances(instance.compute.hostname,
                                instance.compute.login,
                                instance.compute.password,
                                instance.compute.type)
            if 'poweron' in request.POST:
                msg = _("Power On")
                addlogmsg(request.user.username, instance.name, msg)
                conn.start(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'poweroff' in request.POST:
                msg = _("Power Off")
                addlogmsg(request.user.username, instance.name, msg)
                conn.shutdown(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'powercycle' in request.POST:
                msg = _("Power Cycle")
                conn.force_shutdown(name)
                conn.start(name)
                addlogmsg(request.user.username, instance.name, msg)
                return HttpResponseRedirect(request.get_full_path())

            if request.user.is_superuser:

                if 'suspend' in request.POST:
                    msg = _("Suspend")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.suspend(name)
                    return HttpResponseRedirect(request.get_full_path())

                if 'resume' in request.POST:
                    msg = _("Resume")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.resume(name)
                    return HttpResponseRedirect(request.get_full_path())

        except libvirtError as lib_err:
            error_messages.append(lib_err)
            addlogmsg(request.user.username, instance.name, lib_err.message)

    return render(request, 'instances.html', locals())
Beispiel #22
0
def instances(request):
    """
    :param request:
    :return:
    """

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

    error_messages = []
    all_host_vms = {}
    all_user_vms = {}
    computes = Compute.objects.all()

    if not request.user.is_superuser:
        user_instances = UserInstance.objects.filter(user_id=request.user.id)
        for usr_inst in user_instances:
            if connection_manager.host_is_up(
                    usr_inst.instance.compute.type,
                    usr_inst.instance.compute.hostname):
                conn = wvmHostDetails(usr_inst.instance.compute,
                                      usr_inst.instance.compute.login,
                                      usr_inst.instance.compute.password,
                                      usr_inst.instance.compute.type)
                all_user_vms[usr_inst] = conn.get_user_instances(
                    usr_inst.instance.name)
                all_user_vms[usr_inst].update(
                    {'compute_id': usr_inst.instance.compute.id})
    else:
        for comp in computes:
            if connection_manager.host_is_up(comp.type, comp.hostname):
                try:
                    conn = wvmHostDetails(comp, comp.login, comp.password,
                                          comp.type)
                    if conn.get_host_instances():
                        all_host_vms[comp.id,
                                     comp.name] = conn.get_host_instances()
                        for vm, info in conn.get_host_instances().items():
                            try:
                                check_uuid = Instance.objects.get(
                                    compute_id=comp.id, name=vm)
                                if check_uuid.uuid != info['uuid']:
                                    check_uuid.save()
                            except Instance.DoesNotExist:
                                check_uuid = Instance(compute_id=comp.id,
                                                      name=vm,
                                                      uuid=info['uuid'])
                                check_uuid.save()
                    conn.close()
                except libvirtError as lib_err:
                    error_messages.append(lib_err)

    if request.method == 'POST':
        name = request.POST.get('name', '')
        compute_id = request.POST.get('compute_id', '')
        instance = Instance.objects.get(compute_id=compute_id, name=name)
        try:
            conn = wvmInstances(instance.compute.hostname,
                                instance.compute.login,
                                instance.compute.password,
                                instance.compute.type)
            if 'poweron' in request.POST:
                msg = _("Power On")
                addlogmsg(request.user.username, instance.name, msg)
                conn.start(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'poweroff' in request.POST:
                msg = _("Power Off")
                addlogmsg(request.user.username, instance.name, msg)
                conn.shutdown(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'powercycle' in request.POST:
                msg = _("Power Cycle")
                conn.force_shutdown(name)
                conn.start(name)
                addlogmsg(request.user.username, instance.name, msg)
                return HttpResponseRedirect(request.get_full_path())

            if 'getvvfile' in request.POST:
                msg = _("Send console.vv file")
                addlogmsg(request.user.username, instance.name, msg)
                response = HttpResponse(
                    content='',
                    content_type='application/x-virt-viewer',
                    status=200,
                    reason=None,
                    charset='utf-8')
                response.writelines('[virt-viewer]\n')
                response.writelines('type=' + conn.graphics_type(name) + '\n')
                response.writelines('host=' + conn.graphics_listen(name) +
                                    '\n')
                response.writelines('port=' + conn.graphics_port(name) + '\n')
                response.writelines('title=' + conn.domain_name(name) + '\n')
                response.writelines('password='******'\n')
                response.writelines('enable-usbredir=1\n')
                response.writelines('disable-effects=all\n')
                response.writelines('secure-attention=ctrl+alt+ins\n')
                response.writelines('release-cursor=ctrl+alt\n')
                response.writelines('fullscreen=1\n')
                response.writelines('delete-this-file=1\n')
                response[
                    'Content-Disposition'] = 'attachment; filename="console.vv"'
                return response

            if request.user.is_superuser:

                if 'suspend' in request.POST:
                    msg = _("Suspend")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.suspend(name)
                    return HttpResponseRedirect(request.get_full_path())

                if 'resume' in request.POST:
                    msg = _("Resume")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.resume(name)
                    return HttpResponseRedirect(request.get_full_path())

        except libvirtError as lib_err:
            error_messages.append(lib_err)
            addlogmsg(request.user.username, instance.name, lib_err.message)

    return render(request, 'instances.html', locals())
Beispiel #23
0
def instances(request):
    """
    :param request:
    :return:
    """

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

    error_messages = []
    all_host_vms = {}
    all_host_vms_bis = {}
    all_user_vms = {}
    computes = Compute.objects.all()

    if not request.user.is_superuser:
        user_instances = UserInstance.objects.filter(user_id=request.user.id)
        for usr_inst in user_instances:
            if connection_manager.host_is_up(
                    usr_inst.instance.compute.type,
                    usr_inst.instance.compute.hostname):
                conn = wvmHostDetails(usr_inst.instance.compute,
                                      usr_inst.instance.compute.login,
                                      usr_inst.instance.compute.password,
                                      usr_inst.instance.compute.type)
                all_user_vms[usr_inst] = conn.get_user_instances(
                    usr_inst.instance.name)
                all_user_vms[usr_inst].update(
                    {'compute_id': usr_inst.instance.compute.id})
    else:
        for comp in computes:
            if connection_manager.host_is_up(comp.type, comp.hostname):
                try:
                    conn = wvmHostDetails(comp, comp.login, comp.password,
                                          comp.type)
                    if conn.get_host_instances():
                        all_host_vms[comp.id,
                                     comp.name] = conn.get_host_instances()
                        all_host_vms_bis[comp.id, comp.name] = []
                        for vm, info in all_host_vms[comp.id,
                                                     comp.name].items():
                            try:
                                check_uuid = Instance.objects.get(
                                    compute_id=comp.id, name=vm)
                                if check_uuid.uuid != info['uuid']:
                                    check_uuid.save()
                            except Instance.DoesNotExist:
                                check_uuid = Instance(compute_id=comp.id,
                                                      name=vm,
                                                      uuid=info['uuid'])
                                check_uuid.save()
                            all_host_vms_bis[comp.id, comp.name].append(
                                (Instance.objects.get(compute_id=comp.id,
                                                      name=vm), info))
                    conn.close()
                except libvirtError as lib_err:
                    error_messages.append(lib_err)
    if request.method == 'POST':
        name = request.POST.get('name', '')
        compute_id = request.POST.get('compute_id', '')
        instance = Instance.objects.get(compute_id=compute_id, name=name)
        try:
            conn = wvmInstances(instance.compute.hostname,
                                instance.compute.login,
                                instance.compute.password,
                                instance.compute.type)
            if 'poweron' in request.POST:
                msg = _("Power On")
                addlogmsg(request.user.username, instance.name, msg)
                conn.start(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'poweroff' in request.POST:
                msg = _("Power Off")
                addlogmsg(request.user.username, instance.name, msg)
                conn.shutdown(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'powercycle' in request.POST:
                msg = _("Power Cycle")
                conn.force_shutdown(name)
                conn.start(name)
                addlogmsg(request.user.username, instance.name, msg)
                return HttpResponseRedirect(request.get_full_path())

            if request.user.is_superuser:

                if 'suspend' in request.POST:
                    msg = _("Suspend")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.suspend(name)
                    return HttpResponseRedirect(request.get_full_path())

                if 'resume' in request.POST:
                    msg = _("Resume")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.resume(name)
                    return HttpResponseRedirect(request.get_full_path())

        except libvirtError as lib_err:
            error_messages.append(lib_err)
            addlogmsg(request.user.username, instance.name, lib_err.message)

    return render(request, 'instances.html', locals())
Beispiel #24
0
def instances(request):
    """
    :param request:
    :return:
    """

    error_messages = []
    all_host_vms = {}
    all_user_vms = {}
    computes = Compute.objects.all()

    if not request.user.is_superuser:
        user_instances = UserInstance.objects.filter(user_id=request.user.id)
        for usr_inst in user_instances:
            if connection_manager.host_is_up(usr_inst.instance.compute.type,
                                             usr_inst.instance.compute.hostname):
                conn = wvmHostDetails(usr_inst.instance.compute,
                                      usr_inst.instance.compute.login,
                                      usr_inst.instance.compute.password,
                                      usr_inst.instance.compute.type)
                all_user_vms[usr_inst] = conn.get_user_instances(usr_inst.instance.name)
                all_user_vms[usr_inst].update({'compute_id': usr_inst.instance.compute.id})
    else:
        for comp in computes:
            if connection_manager.host_is_up(comp.type, comp.hostname):
                try:
                    conn = wvmHostDetails(comp, comp.login, comp.password, comp.type)
                    if conn.get_host_instances():
                        all_host_vms[comp.id, comp.name] = conn.get_host_instances()
                        for vm, info in conn.get_host_instances().items():
                            try:
                                check_uuid = Instance.objects.get(compute_id=comp.id, name=vm)
                                if check_uuid.uuid != info['uuid']:
                                    check_uuid.save()
                                all_host_vms[comp.id, comp.name][vm]['is_template'] = check_uuid.is_template
                            except Instance.DoesNotExist:
                                check_uuid = Instance(compute_id=comp.id, name=vm, uuid=info['uuid'])
                                check_uuid.save()
                    conn.close()
                except libvirtError as lib_err:
                    error_messages.append(lib_err)

    if request.method == 'POST':
        name = request.POST.get('name', '')
        compute_id = request.POST.get('compute_id', '')
        instance = Instance.objects.get(compute_id=compute_id, name=name)
        try:
            conn = wvmInstances(instance.compute.hostname,
                                instance.compute.login,
                                instance.compute.password,
                                instance.compute.type)
            if 'poweron' in request.POST:
                msg = _("Power On")
                addlogmsg(request.user.username, instance.name, msg)
                conn.start(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'poweroff' in request.POST:
                msg = _("Power Off")
                addlogmsg(request.user.username, instance.name, msg)
                conn.shutdown(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'powercycle' in request.POST:
                msg = _("Power Cycle")
                conn.force_shutdown(name)
                conn.start(name)
                addlogmsg(request.user.username, instance.name, msg)
                return HttpResponseRedirect(request.get_full_path())
            
            if 'getvvfile' in request.POST:
                msg = _("Send console.vv file")
                addlogmsg(request.user.username, instance.name, msg)
                response = HttpResponse(content='', content_type='application/x-virt-viewer', status=200, reason=None, charset='utf-8')
                response.writelines('[virt-viewer]\n')
                response.writelines('type=' + conn.graphics_type(name) + '\n')
                response.writelines('host=' + conn.graphics_listen(name) + '\n')
                response.writelines('port=' + conn.graphics_port(name) + '\n')
                response.writelines('title=' + conn.domain_name(name) + '\n')
                response.writelines('password='******'\n')
                response.writelines('enable-usbredir=1\n')
                response.writelines('disable-effects=all\n')
                response.writelines('secure-attention=ctrl+alt+ins\n')
                response.writelines('release-cursor=ctrl+alt\n')
                response.writelines('fullscreen=1\n')
                response.writelines('delete-this-file=1\n')
                response['Content-Disposition'] = 'attachment; filename="console.vv"'
                return response

            if request.user.is_superuser:

                if 'suspend' in request.POST:
                    msg = _("Suspend")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.suspend(name)
                    return HttpResponseRedirect(request.get_full_path())

                if 'resume' in request.POST:
                    msg = _("Resume")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.resume(name)
                    return HttpResponseRedirect(request.get_full_path())

        except libvirtError as lib_err:
            error_messages.append(lib_err)
            addlogmsg(request.user.username, instance.name, lib_err.message)

    return render(request, 'instances.html', locals())
Beispiel #25
0
    def get_hosts_status(hosts):
        """
        Function return all hosts all vds on host
        """
        all_hosts = []
        flag = 0
        for host in hosts:

            # instances
            errors = []
            instances = []
            time_refresh = 8000
            get_instances = []
            conn = None
            all_hosts.append({
                'id':
                host.id,
                'name':
                host.name,
                'hostname':
                host.hostname,
                'status':
                connection_manager.host_is_up(host.type, host.hostname),
                'type':
                host.type,
                'login':
                host.login,
                'password':
                host.password,
                'instances':
                instances
            })

            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()
                all_hosts[flag]['instances'].append({
                    'name':
                    instance,
                    'status':
                    conn.get_instance_status(instance),
                    'uuid':
                    uuid,
                    'memory':
                    conn.get_instance_memory(instance),
                    'vcpu':
                    conn.get_instance_vcpu(instance),
                    'has_managed_save_image':
                    conn.get_instance_managed_save_image(instance)
                })
            flag = flag + 1
        return all_hosts
Beispiel #26
0
def instances(request):
    """
    :param request:
    :return:
    """

    error_messages = []
    all_host_vms = {}
    all_user_vms = {}
    computes = Compute.objects.all()

    def get_userinstances_info(instance):
        info = {}
        uis = UserInstance.objects.filter(instance=instance)
        info['count'] = uis.count()
        if info['count'] > 0:
            info['first_user'] = uis[0]
        else:
            info['first_user'] = None
        return info

    def refresh_instance_database(comp, vm, info):
        instances = Instance.objects.filter(name=vm)
        if instances.count() > 1:
            for i in instances:
                user_instances_count = UserInstance.objects.filter(
                    instance=i).count()
                if user_instances_count == 0:
                    addlogmsg(request.user.username, i.name,
                              _("Deleting due to multiple records."))
                    i.delete()

        try:
            check_uuid = Instance.objects.get(compute_id=comp["id"], name=vm)
            if check_uuid.uuid != info['uuid']:
                check_uuid.save()

            all_host_vms[comp_info["id"], comp_info["name"],
                         comp_info["status"], comp_info["cpu"],
                         comp_info["mem_size"], comp_info["mem_perc"]][vm][
                             'is_template'] = check_uuid.is_template
            all_host_vms[comp_info["id"], comp_info["name"],
                         comp_info["status"], comp_info["cpu"],
                         comp_info["mem_size"], comp_info["mem_perc"]][vm][
                             'userinstances'] = get_userinstances_info(
                                 check_uuid)
        except Instance.DoesNotExist:
            check_uuid = Instance(compute_id=comp["id"],
                                  name=vm,
                                  uuid=info['uuid'])
            check_uuid.save()

    if not request.user.is_superuser:
        user_instances = UserInstance.objects.filter(user_id=request.user.id)
        for usr_inst in user_instances:
            if connection_manager.host_is_up(
                    usr_inst.instance.compute.type,
                    usr_inst.instance.compute.hostname):
                conn = wvmHostDetails(usr_inst.instance.compute,
                                      usr_inst.instance.compute.login,
                                      usr_inst.instance.compute.password,
                                      usr_inst.instance.compute.type)
                all_user_vms[usr_inst] = conn.get_user_instances(
                    usr_inst.instance.name)
                all_user_vms[usr_inst].update(
                    {'compute_id': usr_inst.instance.compute.id})
    else:
        for comp in computes:
            status = connection_manager.host_is_up(comp.type, comp.hostname)
            if status:
                try:
                    conn = wvmHostDetails(comp, comp.login, comp.password,
                                          comp.type)
                    comp_node_info = conn.get_node_info()
                    comp_mem = conn.get_memory_usage()
                    comp_instances = conn.get_host_instances(True)

                    if comp_instances:
                        comp_info = {
                            "id": comp.id,
                            "name": comp.name,
                            "status": status,
                            "cpu": comp_node_info[3],
                            "mem_size": comp_node_info[2],
                            "mem_perc": comp_mem['percent']
                        }
                        all_host_vms[comp_info["id"], comp_info["name"],
                                     comp_info["status"], comp_info["cpu"],
                                     comp_info["mem_size"],
                                     comp_info["mem_perc"]] = comp_instances
                        for vm, info in comp_instances.items():
                            refresh_instance_database(comp_info, vm, info)

                    conn.close()
                except libvirtError as lib_err:
                    error_messages.append(lib_err)

    if request.method == 'POST':
        name = request.POST.get('name', '')
        compute_id = request.POST.get('compute_id', '')
        instance = Instance.objects.get(compute_id=compute_id, name=name)
        try:
            conn = wvmInstances(instance.compute.hostname,
                                instance.compute.login,
                                instance.compute.password,
                                instance.compute.type)
            if 'poweron' in request.POST:
                msg = _("Power On")
                addlogmsg(request.user.username, instance.name, msg)
                conn.start(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'poweroff' in request.POST:
                msg = _("Power Off")
                addlogmsg(request.user.username, instance.name, msg)
                conn.shutdown(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'powercycle' in request.POST:
                msg = _("Power Cycle")
                conn.force_shutdown(name)
                conn.start(name)
                addlogmsg(request.user.username, instance.name, msg)
                return HttpResponseRedirect(request.get_full_path())

            if 'getvvfile' in request.POST:
                msg = _("Send console.vv file")
                addlogmsg(request.user.username, instance.name, msg)
                response = HttpResponse(
                    content='',
                    content_type='application/x-virt-viewer',
                    status=200,
                    reason=None,
                    charset='utf-8')
                response.writelines('[virt-viewer]\n')
                response.writelines('type=' + conn.graphics_type(name) + '\n')
                response.writelines('host=' + conn.graphics_listen(name) +
                                    '\n')
                response.writelines('port=' + conn.graphics_port(name) + '\n')
                response.writelines('title=' + conn.domain_name(name) + '\n')
                response.writelines('password='******'\n')
                response.writelines('enable-usbredir=1\n')
                response.writelines('disable-effects=all\n')
                response.writelines('secure-attention=ctrl+alt+ins\n')
                response.writelines('release-cursor=ctrl+alt\n')
                response.writelines('fullscreen=1\n')
                response.writelines('delete-this-file=1\n')
                response[
                    'Content-Disposition'] = 'attachment; filename="console.vv"'
                return response

            if request.user.is_superuser:

                if 'suspend' in request.POST:
                    msg = _("Suspend")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.suspend(name)
                    return HttpResponseRedirect(request.get_full_path())

                if 'resume' in request.POST:
                    msg = _("Resume")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.resume(name)
                    return HttpResponseRedirect(request.get_full_path())

        except libvirtError as lib_err:
            error_messages.append(lib_err)
            addlogmsg(request.user.username, instance.name, lib_err.message)

    return render(request, 'instances.html', locals())
Beispiel #27
0
def instances(request):
    """
    :param request:
    :return:
    """

    error_messages = []
    all_host_vms = {}
    all_user_vms = {}
    computes = Compute.objects.all().order_by("name")

    def get_userinstances_info(instance):
        info = {}
        uis = UserInstance.objects.filter(instance=instance)
        info['count'] = uis.count()
        if info['count'] > 0:
            info['first_user'] = uis[0]
        else:
            info['first_user'] = None
        return info

    def refresh_instance_database(comp, vm, info):
        instances = Instance.objects.filter(name=vm)
        if instances.count() > 1:
            for i in instances:
                user_instances_count = UserInstance.objects.filter(instance=i).count()
                if user_instances_count == 0:
                    addlogmsg(request.user.username, i.name, _("Deleting due to multiple records."))
                    i.delete()
        
        try:
            check_uuid = Instance.objects.get(compute_id=comp["id"], name=vm)
            if check_uuid.uuid != info['uuid']:
                check_uuid.save()

            all_host_vms[comp["id"],
                         comp["name"],
                         comp["status"],
                         comp["cpu"],
                         comp["mem_size"],
                         comp["mem_perc"]][vm]['is_template'] = check_uuid.is_template
            all_host_vms[comp["id"],
                         comp["name"],
                         comp["status"],
                         comp["cpu"],
                         comp["mem_size"],
                         comp["mem_perc"]][vm]['userinstances'] = get_userinstances_info(check_uuid)
        except Instance.DoesNotExist:
            check_uuid = Instance(compute_id=comp["id"], name=vm, uuid=info['uuid'])
            check_uuid.save()
    
    if not request.user.is_superuser:
        user_instances = UserInstance.objects.filter(user_id=request.user.id)
        for usr_inst in user_instances:
            if connection_manager.host_is_up(usr_inst.instance.compute.type,
                                             usr_inst.instance.compute.hostname):
                conn = wvmHostDetails(usr_inst.instance.compute,
                                      usr_inst.instance.compute.login,
                                      usr_inst.instance.compute.password,
                                      usr_inst.instance.compute.type)
                all_user_vms[usr_inst] = conn.get_user_instances(usr_inst.instance.name)
                all_user_vms[usr_inst].update({'compute_id': usr_inst.instance.compute.id})
    else:
        for comp in computes:
            status = connection_manager.host_is_up(comp.type, comp.hostname)
            if status:
                try:
                    conn = wvmHostDetails(comp, comp.login, comp.password, comp.type)
                    comp_node_info = conn.get_node_info()
                    comp_mem = conn.get_memory_usage()
                    comp_instances = conn.get_host_instances(True)

                    if comp_instances:
                        comp_info= {
                            "id": comp.id,
                            "name": comp.name,
                            "status": status,
                            "cpu": comp_node_info[3],
                            "mem_size": comp_node_info[2],
                            "mem_perc": comp_mem['percent']
                        }
                        all_host_vms[comp_info["id"], comp_info["name"], comp_info["status"], comp_info["cpu"],
                                     comp_info["mem_size"], comp_info["mem_perc"]] = comp_instances
                        for vm, info in comp_instances.items():
                            refresh_instance_database(comp_info, vm, info)

                    conn.close()
                except libvirtError as lib_err:
                    error_messages.append(lib_err)

    if request.method == 'POST':
        name = request.POST.get('name', '')
        compute_id = request.POST.get('compute_id', '')
        instance = Instance.objects.get(compute_id=compute_id, name=name)
        try:
            conn = wvmInstances(instance.compute.hostname,
                                instance.compute.login,
                                instance.compute.password,
                                instance.compute.type)
            if 'poweron' in request.POST:
                msg = _("Power On")
                addlogmsg(request.user.username, instance.name, msg)
                conn.start(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'poweroff' in request.POST:
                msg = _("Power Off")
                addlogmsg(request.user.username, instance.name, msg)
                conn.shutdown(name)
                return HttpResponseRedirect(request.get_full_path())

            if 'powercycle' in request.POST:
                msg = _("Power Cycle")
                conn.force_shutdown(name)
                conn.start(name)
                addlogmsg(request.user.username, instance.name, msg)
                return HttpResponseRedirect(request.get_full_path())

            if 'getvvfile' in request.POST:
                msg = _("Send console.vv file")
                addlogmsg(request.user.username, instance.name, msg)
                response = HttpResponse(content='', content_type='application/x-virt-viewer', status=200, reason=None, charset='utf-8')
                response.writelines('[virt-viewer]\n')
                response.writelines('type=' + conn.graphics_type(name) + '\n')
                response.writelines('host=' + conn.graphics_listen(name) + '\n')
                response.writelines('port=' + conn.graphics_port(name) + '\n')
                response.writelines('title=' + conn.domain_name(name) + '\n')
                response.writelines('password='******'\n')
                response.writelines('enable-usbredir=1\n')
                response.writelines('disable-effects=all\n')
                response.writelines('secure-attention=ctrl+alt+ins\n')
                response.writelines('release-cursor=ctrl+alt\n')
                response.writelines('fullscreen=1\n')
                response.writelines('delete-this-file=1\n')
                response['Content-Disposition'] = 'attachment; filename="console.vv"'
                return response

            if request.user.is_superuser:

                if 'suspend' in request.POST:
                    msg = _("Suspend")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.suspend(name)
                    return HttpResponseRedirect(request.get_full_path())

                if 'resume' in request.POST:
                    msg = _("Resume")
                    addlogmsg(request.user.username, instance.name, msg)
                    conn.resume(name)
                    return HttpResponseRedirect(request.get_full_path())

        except libvirtError as lib_err:
            error_messages.append(lib_err)
            addlogmsg(request.user.username, instance.name, lib_err.message)

    view_style = settings.VIEW_INSTANCES_LIST_STYLE

    return render(request, 'instances.html', locals())