Example #1
0
def dom_snapshot(request, host_id, vname):
    """

    Snapshot block

    """

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

    snapshot_page = True
    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        dom = conn.lookupByName(vname)
        all_vm = libvirt_func.vds_get_node(conn)
        all_vm_snap = libvirt_func.snapshots_get_node(conn)
        vm_snapshot = libvirt_func.snapshots_get_vds(dom)

        if request.method == 'POST':
            if 'delete' in request.POST:
                snap_name = request.POST.get('name', '')
                libvirt_func.snapshot_delete(dom, snap_name)
                return HttpResponseRedirect('/snapshot/%s/%s/' % (host_id, vname))
            if 'revert' in request.POST:
                snap_name = request.POST.get('name', '')
                libvirt_func.snapshot_revert(dom, snap_name)
                message = _("Successful revert snapshot: ")
                message = message + snap_name

    return render_to_response('snapshot.html', locals(), context_instance=RequestContext(request))
Example #2
0
def snapshot(request, host_id):
    """

    Snapshot block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        all_vm = libvirt_func.vds_get_node(conn)
        all_vm_snap = libvirt_func.snapshots_get_node(conn)

        conn.close()

    if all_vm_snap:
        return HttpResponseRedirect('/snapshot/%s/%s/' %
                                    (host_id, all_vm_snap.keys()[0]))

    return render_to_response('snapshot.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #3
0
def vnc(request, host_id, vname):
    """

    VNC vm's block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        vnc_port = vnc_get_port(conn, vname)
        try:
            vm = Vm.objects.get(host=host_id, vname=vname)

            socket_host = request.META['HTTP_HOST']
            if ':' in socket_host:
                socket_host = re.sub('\:[0-9]+', '', socket_host)

            socket_port = 6080 + int(vnc_port[3:])

            # Kill only owner proccess
            os.system("kill -9 $(ps aux | grep 'websockify %s' | grep -v grep | awk '{ print $2 }')" % socket_port)
            os.system('websockify %s %s:%s -D' % (socket_port, host.ipaddr, vnc_port))
        except:
            vm = None

        conn.close()

    return render_to_response('vnc.html', locals(), context_instance=RequestContext(request))
Example #4
0
def snapshot(request, host_id):
    """

    Snapshot block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        all_vm = libvirt_func.vds_get_node(conn)
        all_vm_snap = libvirt_func.snapshots_get_node(conn)

        conn.close()

    if all_vm_snap:
        return HttpResponseRedirect('/snapshot/%s/%s/' % (host_id, all_vm_snap.keys()[0]))

    return render_to_response('snapshot.html', locals(), context_instance=RequestContext(request))
Example #5
0
def vnc(request, host_id, vname):
    """

    VNC vm's block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        vnc_port = vnc_get_port(conn, vname)
        try:
            vm = Vm.objects.get(host=host_id, vname=vname)

            socket_host = request.META['HTTP_HOST']
            if ':' in socket_host:
                socket_host = re.sub('\:[0-9]+', '', socket_host)

            socket_port = 6080 + int(vnc_port[3:])

            # Kill only owner proccess
            os.system(
                "kill -9 $(ps aux | grep 'websockify %s' | grep -v grep | awk '{ print $2 }')"
                % socket_port)
            os.system('websockify %s %s:%s -D' %
                      (socket_port, host.ipaddr, vnc_port))
        except:
            vm = None

        conn.close()

    return render_to_response('vnc.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #6
0
def dom_snapshot(request, host_id, vname):
    """

    Snapshot block

    """

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

    snapshot_page = True
    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        dom = conn.lookupByName(vname)
        all_vm = libvirt_func.vds_get_node(conn)
        all_vm_snap = libvirt_func.snapshots_get_node(conn)
        vm_snapshot = libvirt_func.snapshots_get_vds(dom)

        if request.method == 'POST':
            if 'delete' in request.POST:
                snap_name = request.POST.get('name', '')
                libvirt_func.snapshot_delete(dom, snap_name)
                return HttpResponseRedirect('/snapshot/%s/%s/' %
                                            (host_id, vname))
            if 'revert' in request.POST:
                snap_name = request.POST.get('name', '')
                libvirt_func.snapshot_revert(dom, snap_name)
                message = _("Successful revert snapshot: ")
                message = message + snap_name

    return render_to_response('snapshot.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #7
0
def overview(request, host_id):
    """

    Overview page.

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    errors = []

    if type(conn) == dict:
        errors.append(conn.values()[0])
    else:
        have_kvm = libvirt_func.hard_accel_node(conn)
        if not have_kvm:
            msg = _('Your CPU doesn\'t support hardware virtualization')
            errors.append(msg)

        all_vm = libvirt_func.vds_get_node(conn)
        host_info = libvirt_func.node_get_info(conn)
        mem_usage = libvirt_func.memory_get_usage(conn)
        cpu_usage = libvirt_func.cpu_get_usage(conn)
        lib_virt_ver = conn.getLibVersion()
        conn_type = conn.getURI()

        if request.method == 'POST':
            vname = request.POST.get('vname', '')
            dom = conn.lookupByName(vname)
            if 'start' in request.POST:
                try:
                    dom.create()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'shutdown' in request.POST:
                try:
                    dom.shutdown()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'destroy' in request.POST:
                try:
                    dom.destroy()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'suspend' in request.POST:
                try:
                    dom.suspend()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'resume' in request.POST:
                try:
                    dom.resume()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)

        conn.close()

    return render_to_response('overview.html', locals(), context_instance=RequestContext(request))
Example #8
0
def storage(request, host_id, pool):
    """

    Storage pool block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/manage/')
    else:

        storages = libvirt_func.storages_get_node(conn)

        if pool is None:
            if len(storages) == 0:
                return HttpResponseRedirect('/storage/%s/add/' % (host_id))
            else:
                return HttpResponseRedirect('/storage/%s/%s/' % (host_id, storages.keys()[0]))

        if pool == 'add':
            if request.method == 'POST':
                if 'addpool' in request.POST:
                    pool_name = request.POST.get('name', '')
                    pool_type = request.POST.get('type', '')
                    pool_target = request.POST.get('target', '')
                    pool_source = request.POST.get('source', '')

                    name_have_symbol = re.search('[^a-zA-Z0-9\_\-]+', pool_name)
                    path_have_symbol = re.search('[^a-zA-Z0-9\/]+', pool_source)

                    errors = []

                    if name_have_symbol or path_have_symbol:
                        msg = _("The host name must not contain any special characters")
                        errors.append(msg)
                    if not pool_name:
                        msg = _("No pool name has been entered")
                        errors.append(msg)
                    elif len(pool_name) > 12:
                        msg = _("The host name must not exceed 12")
                        errors.append(msg)
                    if pool_type == 'logical':
                        if not pool_source:
                            msg = _("No device has been entered")
                            errors.append(msg)
                    if pool_type == 'dir':
                        if not pool_target:
                            msg = _("No path has been entered")
                            errors.append(msg)
                    if pool_name in storages.keys():
                        msg = _("Pool name already use")
                        errors.append(msg)
                    if not errors:
                        try:
                            libvirt_func.new_storage_pool(conn, pool_type, pool_name, pool_source, pool_target)
                            stg = conn.storagePoolLookupByName(pool_name)
                            if pool_type == 'logical':
                                stg.build(0)
                            stg.create(0)
                            stg.setAutostart(1)
                            return HttpResponseRedirect('/storage/%s/%s/' % (host_id, pool_name))
                        except libvirtError as error_msg:
                            errors.append(error_msg.message)
        else:
            all_vm = libvirt_func.vds_get_node(conn)
            form_hdd_size = [10, 20, 40, 80, 160, 320, 640]
            stg = conn.storagePoolLookupByName(pool)

            info = libvirt_func.storage_get_info(stg)

            # refresh storage if acitve
            if info[5] == True:
                stg.refresh(0)
                volumes_info = libvirt_func.volumes_get_info(stg)

            if request.method == 'POST':
                errors = []

                if 'start' in request.POST:
                    try:
                        stg.create(0)
                        msg = 'Start storage pool: %s' % pool
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/%s' % (host_id, pool))
                if 'stop' in request.POST:
                    try:
                        stg.destroy()
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/%s' % (host_id, pool))
                if 'delete' in request.POST:
                    try:
                        stg.undefine()
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/' % host_id)
                if 'addimg' in request.POST:
                    name = request.POST.get('name', '')
                    size = request.POST.get('size', '')
                    img_name = name + '.img'
                    name_have_symbol = re.search('[^a-zA-Z0-9\_\-\.]+', name)
                    if img_name in stg.listVolumes():
                        msg = _("Volume name already use")
                        errors.append(msg)
                    if not name:
                        msg = _("No name has been entered")
                        errors.append(msg)
                    elif len(name) > 20:
                        msg = _("The host name must not exceed 20")
                        errors.append(msg)
                    else:
                        if name_have_symbol:
                            msg = _("The host name must not contain any special characters")
                            errors.append(msg)
                    if not errors:
                        libvirt_func.new_volume(stg, name, size)
                        return HttpResponseRedirect('/storage/%s/%s' % (host_id, pool))
                if 'delimg' in request.POST:
                    img = request.POST.get('img', '')
                    try:
                        vol = stg.storageVolLookupByName(img)
                        vol.delete(0)
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/%s' % (host_id, pool))
                if 'clone' in request.POST:
                    img = request.POST.get('img', '')
                    clone_name = request.POST.get('new_img', '')
                    full_img_name = clone_name + '.img'
                    name_have_symbol = re.search('[^a-zA-Z0-9\_\-\.]+', clone_name)
                    if full_img_name in stg.listVolumes():
                        msg = _("Volume name already use")
                        errors.append(msg)
                    if not clone_name:
                        msg = _("No name has been entered")
                        errors.append(msg)
                    elif len(clone_name) > 20:
                        msg = _("The host name must not exceed 20 characters")
                        errors.append(msg)
                    else:
                        if name_have_symbol:
                            msg = _("The host name must not contain any special characters")
                            errors.append(msg)
                    if not errors:
                        libvirt_func.clone_volume(stg, img, clone_name)
                        return HttpResponseRedirect('/storage/%s/%s' % (host_id, pool))

        conn.close()

    return render_to_response('storage.html', locals(), context_instance=RequestContext(request))
Example #9
0
def newvm(request, host_id):
    """

    Page add new VM.

    """

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

    def add_vm(name, ram, vcpu, image, net, virtio, passwd):
        ram = int(ram) * 1024
        iskvm = re.search('kvm', conn.getCapabilities())
        if iskvm:
            dom_type = 'kvm'
        else:
            dom_type = 'qemu'

        machine = util.get_xml_path(conn.getCapabilities(), "/capabilities/guest/arch/machine/@canonical")
        if not machine:
            machine = 'pc-1.0'

        if re.findall('/usr/libexec/qemu-kvm', conn.getCapabilities()):
            emulator = '/usr/libexec/qemu-kvm'
        elif re.findall('/usr/bin/kvm', conn.getCapabilities()):
            emulator = '/usr/bin/kvm'
        else:
            emulator = '/usr/bin/qemu-system-x86_64'

        img = conn.storageVolLookupByPath(image)
        vol = img.name()
        for storage in all_storages:
            stg = conn.storagePoolLookupByName(storage)
            if stg.info()[0] != 0:
                stg.refresh(0)
                for img in stg.listVolumes():
                    if img == vol:
                        stg_type = util.get_xml_path(stg.XMLDesc(0), "/pool/@type")
                        if stg_type == 'dir':
                            image_type = 'qcow2'
                        else:
                            image_type = 'raw'

        xml = """<domain type='%s'>
                  <name>%s</name>
                  <memory>%s</memory>
                  <currentMemory>%s</currentMemory>
                  <vcpu>%s</vcpu>
                  <os>
                    <type arch='x86_64' machine='%s'>hvm</type>
                    <boot dev='hd'/>
                    <boot dev='cdrom'/>
                    <bootmenu enable='yes'/>
                  </os>
                  <features>
                    <acpi/>
                    <apic/>
                    <pae/>
                  </features>
                  <clock offset='utc'/>
                  <on_poweroff>destroy</on_poweroff>
                  <on_reboot>restart</on_reboot>
                  <on_crash>restart</on_crash>
                  <devices>
                    <emulator>%s</emulator>
                    <disk type='file' device='disk'>
                      <driver name='qemu' type='%s'/>
                      <source file='%s'/>""" % (dom_type, name, ram, ram, vcpu, machine, emulator, image_type, image)

        if virtio:
            xml += """<target dev='vda' bus='virtio'/>"""
        else:
            xml += """<target dev='hda' bus='ide'/>"""

        xml += """</disk>
                    <disk type='file' device='cdrom'>
                      <driver name='qemu' type='raw'/>
                      <source file=''/>
                      <target dev='hdc' bus='ide'/>
                      <readonly/>
                    </disk>"""

        if re.findall("br", net):
            xml += """<interface type='bridge'>
                    <source bridge='%s'/>""" % (net)
        else:
            xml += """<interface type='network'>
                    <source network='%s'/>""" % (net)
        if virtio:
            xml += """<model type='virtio' />"""

        xml += """</interface>
                    <input type='tablet' bus='usb'/>
                    <input type='mouse' bus='ps2'/>
                    <graphics type='vnc' port='-1' autoport='yes' keymap='en-us' passwd='%s'/>
                    <video>
                      <model type='cirrus' vram='9216' heads='1'/>
                    </video>
                    <memballoon model='virtio'>
                    </memballoon>
                  </devices>
                </domain>""" % (passwd)
        conn.defineXML(xml)
        dom = conn.lookupByName(name)
        dom.setAutostart(1)

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        have_kvm = libvirt_func.hard_accel_node(conn)

        try:
            flavors = Flavor.objects.filter().order_by('id')
        except:
            flavors = 'error'

        errors = []

        all_vm = libvirt_func.vds_get_node(conn)
        all_networks = libvirt_func.networks_get_node(conn)
        all_storages = libvirt_func.storages_get_node(conn)
        all_img = libvirt_func.images_get_storages(conn, all_storages)

        if not all_networks:
            msg = _("You haven't defined any virtual networks")
            errors.append(msg)
        if not all_storages:
            msg = _("You haven't defined have any storage pools")
            errors.append(msg)
        if not have_kvm:
            msg = _("Your CPU doesn't support hardware virtualization")
            errors.append(msg)

        hdd_digits_size = [a for a in range(1, 601)]

        if request.method == 'POST':
            if 'add_flavor' in request.POST:
                name = request.POST.get('name', '')
                vcpu = request.POST.get('vcpu', '')
                ram = request.POST.get('ram', '')
                hdd = request.POST.get('hdd', '')

                for flavor in flavors:
                    if name == flavor.name:
                        msg = _("Name already use")
                        errors.append(msg)
                if not errors:
                    flavor_add = Flavor(name=name, vcpu=vcpu, ram=ram, hdd=hdd)
                    flavor_add.save()
                    return HttpResponseRedirect(request.get_full_path())

            if 'del_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                flavor_del = Flavor.objects.get(id=flavor_id)
                flavor_del.delete()
                return HttpResponseRedirect(request.get_full_path())

            if 'newvm' in request.POST:
                net = request.POST.get('network', '')
                storage = request.POST.get('storage', '')
                vname = request.POST.get('name', '')
                hdd_size = request.POST.get('hdd_size', '')
                img = request.POST.get('img', '')
                ram = request.POST.get('ram', '')
                vcpu = request.POST.get('vcpu', '')
                virtio = request.POST.get('virtio', '')

                symbol = re.search('[^a-zA-Z0-9\_\-\.]+', vname)

                if vname in all_vm:
                    msg = _("A virtual machine with this name already exists")
                    errors.append(msg)
                if len(vname) > 12:
                    msg = _("The name of the virtual machine must not exceed 12 characters")
                    errors.append(msg)
                if symbol:
                    msg = _("The name of the virtual machine must not contain any special characters")
                    errors.append(msg)
                if not vname:
                    msg = _("Enter the name of the virtual machine")
                    errors.append(msg)
                if not errors:
                    if not hdd_size:
                        if not img:
                            msg = _("First you need to create an image")
                            errors.append(msg)
                        else:
                            image = libvirt_func.image_get_path(conn, img, all_storages)
                    else:
                        try:
                            stg = conn.storagePoolLookupByName(storage)
                            libvirt_func.new_volume(stg, vname, hdd_size)
                        except libvirtError as msg_error:
                            errors.append(msg_error.message)
                    if not errors:
                        if not img:
                            stg_type = util.get_xml_path(stg.XMLDesc(0), "/pool/@type")
                            if stg_type == 'dir':
                                vol = vname + '.img'
                            else:
                                vol = vname
                            vl = stg.storageVolLookupByName(vol)
                        else:
                            vol = img
                            vl = conn.storageVolLookupByPath(image)

                        image = vl.path()
                        vnc_passwd = ''.join([choice(letters + digits) for i in range(12)])

                        try:
                            add_vm(vname, ram, vcpu, image, net, virtio, vnc_passwd)
                        except libvirtError as msg_error:
                            if hdd_size:
                                vl.delete(0)
                            errors.append(msg_error.message)

                        if not errors:
                            new_vm = Vm(host_id=host_id, vname=vname, vnc_passwd=vnc_passwd)
                            new_vm.save()
                            return HttpResponseRedirect('/vds/%s/%s/' % (host_id, vname))

        conn.close()

    return render_to_response('newvm.html', locals(), context_instance=RequestContext(request))
Example #10
0
def network(request, host_id, pool):
    """

    Networks block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:

        networks = libvirt_func.networks_get_node(conn)

        if pool is None:
            if len(networks) == 0:
                return HttpResponseRedirect('/network/%s/add/' % (host_id))
            else:
                return HttpResponseRedirect('/network/%s/%s/' %
                                            (host_id, networks.keys()[0]))

        if pool == 'add':
            if request.method == 'POST':
                if 'addpool' in request.POST:
                    dhcp = []
                    pool_name = request.POST.get('name', '')
                    net_addr = request.POST.get('net_addr', '')
                    forward = request.POST.get('forward', '')
                    dhcp.append(request.POST.get('dhcp', ''))

                    name_have_symbol = re.search('[^a-zA-Z0-9\_\-]+',
                                                 pool_name)
                    ip_have_symbol = re.search('[^0-9\.\/]+', net_addr)

                    errors = []

                    if not pool_name:
                        msg = _("No pool name has been entered")
                        errors.append(msg)
                    elif len(pool_name) > 12:
                        msg = _("The pool name must not exceed 20 characters")
                        errors.append(msg)
                    else:
                        if name_have_symbol:
                            msg = _(
                                "The pool name must not contain any special characters"
                            )
                            errors.append(msg)
                    if not net_addr:
                        msg = _("No subnet has been entered")
                        errors.append(msg)
                    elif ip_have_symbol:
                        msg = _(
                            "The pool name must not contain any special characters"
                        )
                        errors.append(msg)
                    if pool_name in networks.keys():
                        msg = _("Pool name already in use")
                        errors.append(msg)
                    try:
                        netmask = IP(net_addr).strNetmask()
                        ipaddr = IP(net_addr)
                        gateway = ipaddr[0].strNormal()[-1]
                        if gateway == '0':
                            gw = ipaddr[1].strNormal()
                            dhcp_start = ipaddr[2].strNormal()
                            end = ipaddr.len() - 2
                            dhcp_end = ipaddr[end].strNormal()
                        else:
                            gw = ipaddr[0].strNormal()
                            dhcp_start = ipaddr[1].strNormal()
                            end = ipaddr.len() - 2
                            dhcp_end = ipaddr[end].strNormal()
                        dhcp.append(dhcp_start)
                        dhcp.append(dhcp_end)
                    except:
                        msg = _("Input subnet pool error")
                        errors.append(msg)
                    if not errors:
                        try:
                            libvirt_func.new_network_pool(
                                conn, pool_name, forward, gw, netmask, dhcp)
                            net = conn.networkLookupByName(pool_name)
                            net.create()
                            net.setAutostart(1)
                            return HttpResponseRedirect('/network/%s/%s/' %
                                                        (host_id, pool_name))
                        except libvirtError as error_msg:
                            errors.append(error_msg.message)
        else:
            all_vm = libvirt_func.vds_get_node(conn)
            net = conn.networkLookupByName(pool)

            info = libvirt_func.network_get_info(net)

            if info[0] == True:
                ipv4_net = libvirt_func.network_get_subnet(net)

            if request.method == 'POST':
                if 'start' in request.POST:
                    try:
                        net.create()
                        return HttpResponseRedirect('/network/%s/%s' %
                                                    (host_id, pool))
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                if 'stop' in request.POST:
                    try:
                        net.destroy()
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/network/%s/%s' %
                                                (host_id, pool))
                if 'delete' in request.POST:
                    try:
                        net.undefine()
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/network/%s/' % host_id)

        conn.close()

    return render_to_response('network.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #11
0
def overview(request, host_id):
    """

    Overview page.

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    errors = []

    if type(conn) == dict:
        errors.append(conn.values()[0])
    else:
        have_kvm = libvirt_func.hard_accel_node(conn)
        if not have_kvm:
            msg = _('Your CPU doesn\'t support hardware virtualization')
            errors.append(msg)

        all_vm = libvirt_func.vds_get_node(conn)
        host_info = libvirt_func.node_get_info(conn)
        mem_usage = libvirt_func.memory_get_usage(conn)
        cpu_usage = libvirt_func.cpu_get_usage(conn)
        lib_virt_ver = conn.getLibVersion()
        conn_type = conn.getURI()

        if request.method == 'POST':
            vname = request.POST.get('vname', '')
            dom = conn.lookupByName(vname)
            if 'start' in request.POST:
                try:
                    dom.create()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'shutdown' in request.POST:
                try:
                    dom.shutdown()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'destroy' in request.POST:
                try:
                    dom.destroy()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'suspend' in request.POST:
                try:
                    dom.suspend()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'resume' in request.POST:
                try:
                    dom.resume()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)

        conn.close()

    return render_to_response('overview.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #12
0
def clusters(request):
    """

    Infrastructure page.

    """
    def vds_on_host():
        import virtinst.util as util
        host_mem = conn.getInfo()[1] * 1048576
        try:
            vname = {}
            for vm_id in conn.listDomainsID():
                vm_id = int(vm_id)
                dom = conn.lookupByID(vm_id)
                mem = util.get_xml_path(dom.XMLDesc(0), "/domain/memory")
                mem = int(mem) * 1024
                mem_usage = (mem * 100) / host_mem
                vcpu = util.get_xml_path(dom.XMLDesc(0), "/domain/vcpu")
                vname[dom.name()] = (dom.info()[0], vcpu, mem, mem_usage)
            for vm in conn.listDefinedDomains():
                dom = conn.lookupByName(vm)
                mem = util.get_xml_path(dom.XMLDesc(0), "/domain/memory")
                mem = int(mem) * 1024
                mem_usage = (mem * 100) / host_mem
                vcpu = util.get_xml_path(dom.XMLDesc(0), "/domain/vcpu")
                vname[dom.name()] = (dom.info()[0], vcpu, mem, mem_usage)
            return vname
        except libvirtError as e:
            return e.message

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

    hosts = Host.objects.filter().order_by('id')
    hosts_vms = {}

    for host in hosts:
        try:
            import socket
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(1)
            if host.conn_type == 'ssh':
                s.connect((host.ipaddr, host.ssh_port))
            else:
                s.connect((host.ipaddr, 16509))
            s.close()
            status = 1
        except Exception as err:
            status = 2

        if status == 1:
            conn = libvirt_func.libvirt_conn(host)
            host_info = libvirt_func.node_get_info(conn)
            host_mem = libvirt_func.memory_get_usage(conn)
            hosts_vms[host.id, host.hostname, status, host_info[2],
                      host_mem[0], host_mem[2]] = vds_on_host()
        else:
            hosts_vms[host.id, host.hostname, status, None, None, None] = None

    return render_to_response('clusters.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #13
0
def storage(request, host_id, pool):
    """

    Storage pool block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/manage/')
    else:

        storages = libvirt_func.storages_get_node(conn)

        if pool is None:
            if len(storages) == 0:
                return HttpResponseRedirect('/storage/%s/add/' % (host_id))
            else:
                return HttpResponseRedirect('/storage/%s/%s/' %
                                            (host_id, storages.keys()[0]))

        if pool == 'add':
            if request.method == 'POST':
                if 'addpool' in request.POST:
                    pool_name = request.POST.get('name', '')
                    pool_type = request.POST.get('type', '')
                    pool_target = request.POST.get('target', '')
                    pool_source = request.POST.get('source', '')

                    name_have_symbol = re.search('[^a-zA-Z0-9\_\-]+',
                                                 pool_name)
                    path_have_symbol = re.search('[^a-zA-Z0-9\/]+',
                                                 pool_source)

                    errors = []

                    if name_have_symbol or path_have_symbol:
                        msg = _(
                            "The host name must not contain any special characters"
                        )
                        errors.append(msg)
                    if not pool_name:
                        msg = _("No pool name has been entered")
                        errors.append(msg)
                    elif len(pool_name) > 12:
                        msg = _("The host name must not exceed 12")
                        errors.append(msg)
                    if pool_type == 'logical':
                        if not pool_source:
                            msg = _("No device has been entered")
                            errors.append(msg)
                    if pool_type == 'dir':
                        if not pool_target:
                            msg = _("No path has been entered")
                            errors.append(msg)
                    if pool_name in storages.keys():
                        msg = _("Pool name already use")
                        errors.append(msg)
                    if not errors:
                        try:
                            libvirt_func.new_storage_pool(
                                conn, pool_type, pool_name, pool_source,
                                pool_target)
                            stg = conn.storagePoolLookupByName(pool_name)
                            if pool_type == 'logical':
                                stg.build(0)
                            stg.create(0)
                            stg.setAutostart(1)
                            return HttpResponseRedirect('/storage/%s/%s/' %
                                                        (host_id, pool_name))
                        except libvirtError as error_msg:
                            errors.append(error_msg.message)
        else:
            all_vm = libvirt_func.vds_get_node(conn)
            form_hdd_size = [10, 20, 40, 80, 160, 320, 640]
            stg = conn.storagePoolLookupByName(pool)

            info = libvirt_func.storage_get_info(stg)

            # refresh storage if acitve
            if info[5] == True:
                stg.refresh(0)
                volumes_info = libvirt_func.volumes_get_info(stg)

            if request.method == 'POST':
                errors = []

                if 'start' in request.POST:
                    try:
                        stg.create(0)
                        msg = 'Start storage pool: %s' % pool
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/%s' %
                                                (host_id, pool))
                if 'stop' in request.POST:
                    try:
                        stg.destroy()
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/%s' %
                                                (host_id, pool))
                if 'delete' in request.POST:
                    try:
                        stg.undefine()
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/' % host_id)
                if 'addimg' in request.POST:
                    name = request.POST.get('name', '')
                    size = request.POST.get('size', '')
                    img_name = name + '.img'
                    name_have_symbol = re.search('[^a-zA-Z0-9\_\-\.]+', name)
                    if img_name in stg.listVolumes():
                        msg = _("Volume name already use")
                        errors.append(msg)
                    if not name:
                        msg = _("No name has been entered")
                        errors.append(msg)
                    elif len(name) > 20:
                        msg = _("The host name must not exceed 20")
                        errors.append(msg)
                    else:
                        if name_have_symbol:
                            msg = _(
                                "The host name must not contain any special characters"
                            )
                            errors.append(msg)
                    if not errors:
                        libvirt_func.new_volume(stg, name, size)
                        return HttpResponseRedirect('/storage/%s/%s' %
                                                    (host_id, pool))
                if 'delimg' in request.POST:
                    img = request.POST.get('img', '')
                    try:
                        vol = stg.storageVolLookupByName(img)
                        vol.delete(0)
                    except libvirtError as error_msg:
                        errors.append(error_msg.message)
                    return HttpResponseRedirect('/storage/%s/%s' %
                                                (host_id, pool))
                if 'clone' in request.POST:
                    img = request.POST.get('img', '')
                    clone_name = request.POST.get('new_img', '')
                    full_img_name = clone_name + '.img'
                    name_have_symbol = re.search('[^a-zA-Z0-9\_\-\.]+',
                                                 clone_name)
                    if full_img_name in stg.listVolumes():
                        msg = _("Volume name already use")
                        errors.append(msg)
                    if not clone_name:
                        msg = _("No name has been entered")
                        errors.append(msg)
                    elif len(clone_name) > 20:
                        msg = _("The host name must not exceed 20 characters")
                        errors.append(msg)
                    else:
                        if name_have_symbol:
                            msg = _(
                                "The host name must not contain any special characters"
                            )
                            errors.append(msg)
                    if not errors:
                        libvirt_func.clone_volume(stg, img, clone_name)
                        return HttpResponseRedirect('/storage/%s/%s' %
                                                    (host_id, pool))

        conn.close()

    return render_to_response('storage.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #14
0
def newvm(request, host_id):
    """

    Page add new VM.

    """

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

    def add_vm(name, ram, vcpu, image, net, virtio, passwd):
        ram = int(ram) * 1024
        iskvm = re.search('kvm', conn.getCapabilities())
        if iskvm:
            dom_type = 'kvm'
        else:
            dom_type = 'qemu'

        machine = util.get_xml_path(
            conn.getCapabilities(),
            "/capabilities/guest/arch/machine/@canonical")
        if not machine:
            machine = 'pc-1.0'

        if re.findall('/usr/libexec/qemu-kvm', conn.getCapabilities()):
            emulator = '/usr/libexec/qemu-kvm'
        elif re.findall('/usr/bin/kvm', conn.getCapabilities()):
            emulator = '/usr/bin/kvm'
        else:
            emulator = '/usr/bin/qemu-system-x86_64'

        img = conn.storageVolLookupByPath(image)
        vol = img.name()
        for storage in all_storages:
            stg = conn.storagePoolLookupByName(storage)
            if stg.info()[0] != 0:
                stg.refresh(0)
                for img in stg.listVolumes():
                    if img == vol:
                        stg_type = util.get_xml_path(stg.XMLDesc(0),
                                                     "/pool/@type")
                        if stg_type == 'dir':
                            image_type = 'qcow2'
                        else:
                            image_type = 'raw'

        xml = """<domain type='%s'>
                  <name>%s</name>
                  <memory>%s</memory>
                  <currentMemory>%s</currentMemory>
                  <vcpu>%s</vcpu>
                  <os>
                    <type arch='x86_64' machine='%s'>hvm</type>
                    <boot dev='hd'/>
                    <boot dev='cdrom'/>
                    <bootmenu enable='yes'/>
                  </os>
                  <features>
                    <acpi/>
                    <apic/>
                    <pae/>
                  </features>
                  <clock offset='utc'/>
                  <on_poweroff>destroy</on_poweroff>
                  <on_reboot>restart</on_reboot>
                  <on_crash>restart</on_crash>
                  <devices>
                    <emulator>%s</emulator>
                    <disk type='file' device='disk'>
                      <driver name='qemu' type='%s'/>
                      <source file='%s'/>""" % (dom_type, name, ram, ram, vcpu,
                                                machine, emulator, image_type,
                                                image)

        if virtio:
            xml += """<target dev='vda' bus='virtio'/>"""
        else:
            xml += """<target dev='hda' bus='ide'/>"""

        xml += """</disk>
                    <disk type='file' device='cdrom'>
                      <driver name='qemu' type='raw'/>
                      <source file=''/>
                      <target dev='hdc' bus='ide'/>
                      <readonly/>
                    </disk>"""

        if re.findall("br", net):
            xml += """<interface type='bridge'>
                    <source bridge='%s'/>""" % (net)
        else:
            xml += """<interface type='network'>
                    <source network='%s'/>""" % (net)
        if virtio:
            xml += """<model type='virtio' />"""

        xml += """</interface>
                    <input type='tablet' bus='usb'/>
                    <input type='mouse' bus='ps2'/>
                    <graphics type='vnc' port='-1' autoport='yes' keymap='en-us' passwd='%s'/>
                    <video>
                      <model type='cirrus' vram='9216' heads='1'/>
                    </video>
                    <memballoon model='virtio'>
                    </memballoon>
                  </devices>
                </domain>""" % (passwd)
        conn.defineXML(xml)
        dom = conn.lookupByName(name)
        dom.setAutostart(1)

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        have_kvm = libvirt_func.hard_accel_node(conn)

        try:
            flavors = Flavor.objects.filter().order_by('id')
        except:
            flavors = 'error'

        errors = []

        all_vm = libvirt_func.vds_get_node(conn)
        all_networks = libvirt_func.networks_get_node(conn)
        all_storages = libvirt_func.storages_get_node(conn)
        all_img = libvirt_func.images_get_storages(conn, all_storages)

        if not all_networks:
            msg = _("You haven't defined any virtual networks")
            errors.append(msg)
        if not all_storages:
            msg = _("You haven't defined have any storage pools")
            errors.append(msg)
        if not have_kvm:
            msg = _("Your CPU doesn't support hardware virtualization")
            errors.append(msg)

        hdd_digits_size = [a for a in range(1, 601)]

        if request.method == 'POST':
            if 'add_flavor' in request.POST:
                name = request.POST.get('name', '')
                vcpu = request.POST.get('vcpu', '')
                ram = request.POST.get('ram', '')
                hdd = request.POST.get('hdd', '')

                for flavor in flavors:
                    if name == flavor.name:
                        msg = _("Name already use")
                        errors.append(msg)
                if not errors:
                    flavor_add = Flavor(name=name, vcpu=vcpu, ram=ram, hdd=hdd)
                    flavor_add.save()
                    return HttpResponseRedirect(request.get_full_path())

            if 'del_flavor' in request.POST:
                flavor_id = request.POST.get('flavor', '')
                flavor_del = Flavor.objects.get(id=flavor_id)
                flavor_del.delete()
                return HttpResponseRedirect(request.get_full_path())

            if 'newvm' in request.POST:
                net = request.POST.get('network', '')
                storage = request.POST.get('storage', '')
                vname = request.POST.get('name', '')
                hdd_size = request.POST.get('hdd_size', '')
                img = request.POST.get('img', '')
                ram = request.POST.get('ram', '')
                vcpu = request.POST.get('vcpu', '')
                virtio = request.POST.get('virtio', '')

                symbol = re.search('[^a-zA-Z0-9\_\-\.]+', vname)

                if vname in all_vm:
                    msg = _("A virtual machine with this name already exists")
                    errors.append(msg)
                if len(vname) > 12:
                    msg = _(
                        "The name of the virtual machine must not exceed 12 characters"
                    )
                    errors.append(msg)
                if symbol:
                    msg = _(
                        "The name of the virtual machine must not contain any special characters"
                    )
                    errors.append(msg)
                if not vname:
                    msg = _("Enter the name of the virtual machine")
                    errors.append(msg)
                if not errors:
                    if not hdd_size:
                        if not img:
                            msg = _("First you need to create an image")
                            errors.append(msg)
                        else:
                            image = libvirt_func.image_get_path(
                                conn, img, all_storages)
                    else:
                        try:
                            stg = conn.storagePoolLookupByName(storage)
                            libvirt_func.new_volume(stg, vname, hdd_size)
                        except libvirtError as msg_error:
                            errors.append(msg_error.message)
                    if not errors:
                        if not img:
                            stg_type = util.get_xml_path(
                                stg.XMLDesc(0), "/pool/@type")
                            if stg_type == 'dir':
                                vol = vname + '.img'
                            else:
                                vol = vname
                            vl = stg.storageVolLookupByName(vol)
                        else:
                            vol = img
                            vl = conn.storageVolLookupByPath(image)

                        image = vl.path()
                        vnc_passwd = ''.join(
                            [choice(letters + digits) for i in range(12)])

                        try:
                            add_vm(vname, ram, vcpu, image, net, virtio,
                                   vnc_passwd)
                        except libvirtError as msg_error:
                            if hdd_size:
                                vl.delete(0)
                            errors.append(msg_error.message)

                        if not errors:
                            new_vm = Vm(host_id=host_id,
                                        vname=vname,
                                        vnc_passwd=vnc_passwd)
                            new_vm.save()
                            return HttpResponseRedirect('/vds/%s/%s/' %
                                                        (host_id, vname))

        conn.close()

    return render_to_response('newvm.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #15
0
def vds(request, host_id, vname):
    """

    VDS block

    """

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

    host = Host.objects.get(id=host_id)
    conn = libvirt_func.libvirt_conn(host)

    if type(conn) == dict:
        return HttpResponseRedirect('/overview/%s/' % host_id)
    else:
        all_vm = libvirt_func.vds_get_node(conn)
        dom = conn.lookupByName(vname)

        try:
            vm = Vm.objects.get(vname=vname)
        except:
            vm = None

        dom_info = libvirt_func.vds_get_info(dom)
        cpu_usage = libvirt_func.vds_cpu_usage(conn, dom)
        mem_usage = libvirt_func.vds_memory_usage(conn, dom)

        storages = libvirt_func.storages_get_node(conn)
        hdd_image = libvirt_func.vds_get_hdd(conn, dom, storages)
        iso_images = sorted(libvirt_func.get_all_media(conn, storages))
        media = libvirt_func.vds_get_media(conn, dom)

        errors = []

        if request.method == 'POST':
            if 'start' in request.POST:
                try:
                    dom.create()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'power' in request.POST:
                if 'shutdown' == request.POST.get('power', ''):
                    try:
                        dom.shutdown()
                        return HttpResponseRedirect(request.get_full_path())
                    except libvirtError as msg_error:
                        errors.append(msg_error.message)
                if 'destroy' == request.POST.get('power', ''):
                    try:
                        dom.destroy()
                        return HttpResponseRedirect(request.get_full_path())
                    except libvirtError as msg_error:
                        errors.append(msg_error.message)
            if 'suspend' in request.POST:
                try:
                    dom.suspend()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'resume' in request.POST:
                try:
                    dom.resume()
                    return HttpResponseRedirect(request.get_full_path())
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'delete' in request.POST:
                try:
                    if dom.info()[0] == 1:
                        dom.destroy()
                    if request.POST.get('image', ''):
                        libvirt_func.vds_remove_hdd(conn, dom)
                    try:
                        vm = Vm.objects.get(host=host_id, vname=vname)
                        vm.delete()
                    except:
                        pass
                    dom.undefine()
                    return HttpResponseRedirect('/overview/%s/' % host_id)
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'snapshot' in request.POST:
                try:
                    libvirt_func.vds_create_snapshot(dom)
                    messages = []
                    msg = _("Create snapshot for instance successful")
                    messages.append(msg)
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
            if 'remove_iso' in request.POST:
                image = request.POST.get('iso_img', '')
                libvirt_func.vds_umount_iso(conn, dom, image, storages)
                return HttpResponseRedirect(request.get_full_path())
            if 'add_iso' in request.POST:
                image = request.POST.get('iso_img', '')
                libvirt_func.vds_mount_iso(conn, dom, image, storages)
                return HttpResponseRedirect(request.get_full_path())
            if 'vnc_pass' in request.POST:
                from string import letters, digits
                from random import choice

                passwd = ''.join([choice(letters + digits) for i in range(12)])
                try:
                    libvirt_func.vds_set_vnc_passwd(conn, dom, passwd)
                    vnc_pass = Vm(host_id=host_id, vname=vname, vnc_passwd=passwd)
                    vnc_pass.save()
                except libvirtError as msg_error:
                    errors.append(msg_error.message)
                return HttpResponseRedirect(request.get_full_path())

        conn.close()

    return render_to_response('vds.html', locals(), context_instance=RequestContext(request))