Example #1
0
    def test_view_modify_confirm_quota_over(self):
        args = (self.cluster.slug, self.vm.hostname)
        url = '/cluster/%s/%s/edit/confirm' % args

        user = User(id=52, username='******')
        user.set_password('secret2')
        user.save()
        user.grant('modify', self.vm)
        profile = user.get_profile()
        self.vm.owner = profile
        self.vm.save()

        self.cluster.set_quota(profile, dict(ram=1000, disk=2000,
                                             virtual_cpus=10))

        os_list = cluster_os_list(self.cluster)
        edit_form = dict(vcpus=2000,
            acpi=True,
            disk_cache='default',
            initrd_path='',
            kernel_args='ro',
            kvm_flag='',
            mem_path='',
            migration_downtime=30,
            security_domain='',
            security_model='none',
            usb_mouse='',
            use_chroot=False,
            use_localtime=False,
            vnc_bind_address='0.0.0.0',
            vnc_tls=False,
            vnc_x509_path='',
            vnc_x509_verify=False,
            memory=512,
            os='image+debian-osgeo',
            disk_type='paravirtual',
            boot_order='disk',
            nic_type='paravirtual',
            nic_count=1,
            nic_count_original=1,
            nic_link_0='br0',
            nic_mac_0='aa:bb:00:00:33:d2',
            root_path='/dev/vda1',
            kernel_path='/boot/vmlinuz-2.32.6-27-generic',
            serial_console=True,
            cdrom_image_path='')
        data = {'rapi_dict':json.dumps(edit_form), 'save':True}

        # regular user
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        session = self.c.session
        session['edit_form'] = edit_form
        session['os_list'] = os_list
        session.save()
        response = self.c.post(url, data)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response, 'ganeti/virtual_machine/edit_confirm.html')
        self.c.logout()
Example #2
0
    def __init__(self, vm, initial=None, *args, **kwargs):
        super(VirtualMachineForm, self).__init__(initial, *args, **kwargs)

        # Set owner on form
        try:
            self.owner
        except AttributeError:
            self.owner = vm.owner

        # Setup os choices
        os_list = cluster_os_list(vm.cluster)
        self.fields['os'].choices = os_list

        for field in self.always_required:
            self.fields[field].required = True
        # If the required property is set on a child class,
        #  require those form fields   
        try:
            if self.required:
                for field in self.required:
                    self.fields[field].required = True
        except AttributeError:
            pass

        # Need to set initial values from vm.info as these are not saved
        #  per the vm model.
        if vm.info:
            info = vm.info
            hvparam = info['hvparams']
            # XXX Convert ram string since it comes out
            #  from ganeti as an int and the DataVolumeField does not like
            #  ints.
            self.fields['vcpus'].initial = info['beparams']['vcpus']
            self.fields['memory'].initial = str(info['beparams']['memory'])

            # always take the larger nic count.  this ensures that if nics are
            # being removed that they will be in the form as Nones
            self.nics = len(info['nic.links'])
            nic_count = int(initial.get('nic_count', 1)) if initial else 1
            nic_count = self.nics if self.nics > nic_count else nic_count
            self.fields['nic_count'].initial = nic_count
            self.nic_fields = xrange(nic_count)
            for i in xrange(nic_count):
                link = forms.CharField(label=_('NIC/%s Link' % i), max_length=255, required=True)
                self.fields['nic_link_%s' % i] = link
                mac = MACAddressField(label=_('NIC/%s Mac' % i), required=True)
                self.fields['nic_mac_%s' % i] = mac
                if i < self.nics:
                    mac.initial = info['nic.macs'][i]
                    link.initial = info['nic.links'][i]

            self.fields['os'].initial = info['os']
            
            try:
                if self.hvparam_fields:
                    for field in self.hvparam_fields:
                        self.fields[field].initial = hvparam.get(field)
            except AttributeError:
                pass
Example #3
0
File: edit.py Project: bsu/GWM2
    def test_view_modify_quota_over(self):
        vm = globals()['vm']
        args = (cluster.slug, vm.hostname)
        url = '/cluster/%s/%s/edit' % args

        user = User(id=52, username='******')
        user.set_password('secret2')
        user.save()
        user.grant('modify', vm)
        profile = user.get_profile()
        vm.owner = profile
        vm.save()

        cluster.set_quota(profile, dict(ram=1000, disk=2000, virtual_cpus=10))

        ## POST
        os_list = cluster_os_list(cluster)
        data = dict(vcpus=2000,
            acpi=True,
            disk_cache='default',
            initrd_path='',
            kernel_args='ro',
            kvm_flag='',
            mem_path='',
            migration_downtime=30,
            security_domain='',
            security_model='none',
            usb_mouse='',
            use_chroot=False,
            use_localtime=False,
            vnc_bind_address='0.0.0.0',
            vnc_tls=False,
            vnc_x509_path='',
            vnc_x509_verify=False,
            memory=512,
            os='image+debian-osgeo',
            disk_type='paravirtual',
            boot_order='disk',
            nic_type='paravirtual',
            nic_count=1,
            nic_count_original=1,
            nic_link_0='br0',
            nic_mac_0='aa:bb:00:00:33:d2',
            root_path='/dev/vda1',
            kernel_path='/boot/vmlinuz-2.32.6-27-generic',
            serial_console=True,
            cdrom_image_path='')

        user.grant('modify', vm)
        self.assertTrue(c.login(username=user.username, password='******'))
        self.assertFalse(user.is_superuser)
        session = c.session
        session['os_list'] = os_list
        session.save()
        response = c.post(url, data)
        self.assertEqual(200, response.status_code) # 302 if success (BAD)
        self.assertTemplateUsed(response, 'ganeti/virtual_machine/edit_kvm.html')
        user.revoke_all(vm)
        c.logout()
Example #4
0
def reinstall(request, cluster_slug, instance):
    """
    Reinstall a VM.
    """

    user = request.user
    instance, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    # Check permissions.
    # XXX Reinstalling is somewhat similar to
    # deleting in that you destroy data,
    # so use that for now.
    if not (
        user.is_superuser or
        user.has_any_perms(instance, ["remove", "admin"]) or
            user.has_perm("admin", cluster)):
        raise Http403(NO_PRIVS)

    if request.method == 'GET':
        return render_to_response(
            "ganeti/virtual_machine/reinstall.html",
            {'vm': instance, 'oschoices': cluster_os_list(cluster),
             'current_os': instance.operating_system,
             'cluster': cluster},
            context_instance=RequestContext(request),
        )

    elif request.method == 'POST':
        # Reinstall instance
        if "os" in request.POST:
            os = request.POST["os"]
        else:
            os = instance.operating_system

        # XXX no_startup=True prevents quota circumventions.
        # possible future solution would be a checkbox
        # asking whether they want to start up, and check
        # quota here if they do (would also involve
        # checking whether this VM is already running and subtracting that)

        job_id = instance.rapi \
            .ReinstallInstance(instance.hostname, os=os, no_startup=True)
        job = Job.objects.create(job_id=job_id, obj=instance, cluster=cluster)
        VirtualMachine.objects \
            .filter(id=instance.id).update(last_job=job, ignore_cache=True)

        # log information
        log_action('VM_REINSTALL', user, instance, job)

        return HttpResponseRedirect(
            reverse('instance-detail', args=[cluster.slug, instance.hostname]))
def reinstall(request, cluster_slug, instance):
    """
    Reinstall a VM.
    """

    user = request.user
    instance, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    # Check permissions.
    # XXX Reinstalling is somewhat similar to deleting in that you destroy data,
    # so use that for now.
    if not (
        user.is_superuser or
        user.has_any_perms(instance, ["remove", "admin"]) or
        user.has_perm("admin", cluster)
        ):
        raise Http403(NO_PRIVS)

    if request.method == 'GET':
        return render_to_response(
            "ganeti/virtual_machine/reinstall.html",
            {'vm': instance, 'oschoices': cluster_os_list(cluster),
             'current_os': instance.operating_system,
             'cluster':cluster},
            context_instance=RequestContext(request),
        )

    elif request.method == 'POST':
        # Reinstall instance
        if "os" in request.POST:
            os = request.POST["os"]
        else:
            os = instance.operating_system

        # XXX no_startup=True prevents quota circumventions. possible future solution would be a checkbox
        # asking whether they want to start up, and check quota here if they do (would also involve
        # checking whether this VM is already running and subtracting that)

        job_id = instance.rapi.ReinstallInstance(instance.hostname, os=os, no_startup=True)
        job = Job.objects.create(job_id=job_id, obj=instance, cluster=cluster)
        VirtualMachine.objects.filter(id=instance.id).update(last_job=job, ignore_cache=True)

        # log information
        log_action('VM_REINSTALL', user, instance, job)

        return HttpResponseRedirect(
            reverse('instance-detail', args=[cluster.slug, instance.hostname]))
def cluster_options(request):
    """
    Ajax view for retrieving node and operating system choices for a given
    cluster.
    """
    cluster_id = request.GET.get('cluster_id', None)
    cluster = get_object_or_404(Cluster, id__exact=cluster_id)

    user = request.user
    if not (user.is_superuser or user.has_any_perms(cluster, ['admin', 'create_vm'])):
        raise Http403(
            _('You do not have permissions to view this cluster'))

    oslist = cluster_os_list(cluster)
    nodes = [str(h) for h in cluster.nodes.values_list('hostname', flat=True)]
    content = json.dumps({'nodes':nodes, 'os':oslist})
    return HttpResponse(content, mimetype='application/json')
Example #7
0
    def __init__(self, user, *args, **kwargs):
        self.user = user
        initial = kwargs.get('initial', None)

        # If data is not passed by initial kwarg (as in POST data)
        #   assign initial to self.data as self.data contains POST
        #   data.
        if initial is None and args:
            initial = args[0]

        cluster = None
        if initial:
            if 'cluster' in initial and initial['cluster']:
                try:
                    cluster = Cluster.objects.get(pk=initial['cluster'])
                except Cluster.DoesNotExist:
                    # defer to clean function to return errors
                    pass

            # Load disks and nics. Prefer raw fields, but unpack from dicts
            # if the raw fields are not available.  This allows modify and
            # API calls to use a cleaner syntax
            if 'disks' in initial and not 'disk_count' in initial:
                disks = initial['disks']
                initial['disk_count'] = disk_count = len(disks)
                for i, disk in enumerate(disks):
                    initial['disk_size_%s' % i] = disk['size']
            else:
                disk_count = int(initial.get('disk_count', 1))
            if 'nics' in initial and not 'nic_count' in initial:
                nics = initial['nics']
                initial['nic_count'] = nic_count = len(nics)
                for i, disk in enumerate(nics):
                    initial['nic_mode_%s' % i] = disk['mode']
                    initial['nic_link_%s' % i] = disk['link']
            else:
                nic_count = int(initial.get('nic_count', 1))
        else:
            disk_count = 1
            nic_count = 1

        super(NewVirtualMachineForm, self).__init__(*args, **kwargs)

        # Make sure vcpus is required for this form. Don't want to go through
        #  the trouble of overriding the model field.
        self.fields['vcpus'].required = True

        if cluster is not None and cluster.info is not None:
            # set choices based on selected cluster if given
            oslist = cluster_os_list(cluster)
            nodelist = [str(h) for h in cluster.nodes.values_list('hostname', flat=True)]
            nodes = zip(nodelist, nodelist)
            nodes.insert(0, self.empty_field)
            oslist.insert(0, self.empty_field)
            self.fields['pnode'].choices = nodes
            self.fields['snode'].choices = nodes
            self.fields['os'].choices = oslist

            # must have at least two nodes to use drbd
            if len(nodes) == 2:
                self.fields['disk_template'].choices = self.templates_single

            hv = initial.get('hypervisor', None)
            if hv is not None:
                defaults = cluster_default_info(cluster, hv)
            else:
                defaults = cluster_default_info(cluster)
                hv = defaults['hypervisor']
            if defaults['iallocator'] != '' :
                self.fields['iallocator'].initial = True
                self.fields['iallocator_hostname'] = forms.CharField(
                                        initial=defaults['iallocator'],
                                        required=False,
                                        widget = forms.HiddenInput())
            self.fields['vcpus'].initial = defaults['vcpus']
            self.fields['memory'].initial = defaults['memory']
            self.fields['hypervisor'].choices = defaults['hypervisors']
            self.fields['hypervisor'].initial = hv
            self.create_nic_fields(nic_count, defaults)

            if hv == 'kvm':
                self.fields['serial_console'].initial = defaults['serial_console']


            # Set field choices and hypervisor
            if hv == 'kvm' or hv == 'xen-pvm':
                self.fields['root_path'].initial = defaults['root_path']
                self.fields['kernel_path'].initial = defaults['kernel_path']
            if hv == 'kvm' or hv == 'xen-hvm':
                self.fields['nic_type'].choices = defaults['nic_types']
                self.fields['disk_type'].choices = defaults['disk_types']
                self.fields['boot_order'].choices = defaults['boot_devices']

                self.fields['nic_type'].initial = defaults['nic_type']
                self.fields['disk_type'].initial = defaults['disk_type']
                self.fields['boot_order'].initial = defaults['boot_order']
            if hv == 'xen-pvm':
                for field in self.pvm_exclude_fields:
                    del self.fields[field]
        else:
            self.create_nic_fields(nic_count)

        self.create_disk_fields(disk_count)

        # set cluster choices based on the given owner
        if initial and 'owner' in initial and initial['owner']:
            try:
                self.owner = ClusterUser.objects.get(pk=initial['owner']).cast()
            except ClusterUser.DoesNotExist:
                self.owner = None
        else:
            self.owner = None

        # Set up owner and cluster choices.
        if user.is_superuser:
            # Superusers may do whatever they like.
            self.fields['owner'].queryset = ClusterUser.objects.all()
            self.fields['cluster'].queryset = Cluster.objects.all()
        else:
            # Fill out owner choices. Remember, the list of owners is a list
            # of tuple(ClusterUser.id, label). If you put ids from other
            # Models into this, no magical correction will be applied and you
            # will assign permissions to the wrong owner; see #2007.
            owners = [(u'', u'---------')]
            for group in user.groups.all():
                owners.append((group.organization.id, group.name))
            if user.has_any_perms(Cluster, ['admin','create_vm'], False):
                profile = user.get_profile()
                owners.append((profile.id, profile.name))
            self.fields['owner'].choices = owners

            # Set cluster choices.  If an owner has been selected then filter
            # by the owner.  Otherwise show everything the user has access to
            # through themselves or any groups they are a member of
            if self.owner:
                q = self.owner.get_objects_any_perms(Cluster, ['admin','create_vm'])
            else:
                q = user.get_objects_any_perms(Cluster, ['admin','create_vm'])
            self.fields['cluster'].queryset = q
Example #8
0
    def test_view_modify(self):
        """
        Test modifying an instance
        """

        args = (self.cluster.slug, self.vm.hostname)
        url = '/cluster/%s/%s/edit' % args

        user = User(id=52, username='******')
        user.set_password('secret2')
        user.save()

        ## GET
        # Anonymous User
        response = self.c.get(url)
        self.assertEqual(302, response.status_code)

        # User with Modify Permissions
        user.grant('modify', self.vm)
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        self.assertFalse(user.is_superuser)
        self.assertTrue(user.has_perm('modify', self.vm))
        self.assertFalse(user.has_perm('admin', self.vm))
        response = self.c.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response,
                                'ganeti/virtual_machine/edit_kvm.html')
        user.revoke_all(self.vm)
        self.c.logout()

        # User with Admin Permissions
        user.grant('admin', self.vm)
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        self.assertFalse(user.is_superuser)
        response = self.c.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response,
                                'ganeti/virtual_machine/edit_kvm.html')
        user.revoke_all(self.vm)
        self.c.logout()

        # Superuser
        user.is_superuser = True
        user.save()
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        response = self.c.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response,
                                'ganeti/virtual_machine/edit_kvm.html')
        self.c.logout()
        user.is_superuser = False
        user.save()

        ## POST
        os_list = cluster_os_list(self.cluster)
        data = dict(vcpus=2,
                    acpi=True,
                    disk_cache='default',
                    initrd_path='',
                    kernel_args='ro',
                    kvm_flag='',
                    mem_path='',
                    migration_downtime=30,
                    security_domain='',
                    security_model='none',
                    usb_mouse='',
                    use_chroot=False,
                    use_localtime=False,
                    vnc_bind_address='0.0.0.0',
                    vnc_tls=False,
                    vnc_x509_path='',
                    vnc_x509_verify=False,
                    memory=512,
                    os='image+debian-osgeo',
                    disk_type='paravirtual',
                    boot_order='disk',
                    nic_type='paravirtual',
                    nic_count=1,
                    nic_count_original=1,
                    nic_link_0='br0',
                    nic_mac_0='aa:bb:00:00:33:d2',
                    root_path='/dev/vda1',
                    kernel_path='/boot/vmlinuz-2.32.6-27-generic',
                    serial_console=True,
                    cdrom_image_path='',
                    cdrom2_image_path='')

        # Required Values
        user.grant('modify', self.vm)
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        session = self.c.session
        session['os_list'] = os_list
        session.save()
        for property in ['vcpus', 'memory', 'disk_type', 'boot_order',
                         'nic_type']:
            data_ = data.copy()
            del data_[property]
            self.assertFalse(user.is_superuser)
            response = self.c.post(url, data_)
            # If failure then a field that is not required by the model, but
            #  should be required by the form, is not being required by
            #  the form. See the ModifyVirtualMachineForm.required field.
            self.assertNotEqual(response.context['form'][property].errors,
                                [], msg=property)
            self.assertEqual(200, response.status_code)  # 302 if success (BAD)
            self.assertEqual('text/html; charset=utf-8',
                             response['content-type'])
            self.assertTemplateUsed(response,
                                    'ganeti/virtual_machine/edit_kvm.html')
        self.c.logout()
        user.revoke_all(self.vm)

        # Anonymous User
        response = self.c.post(url, data)
        self.assertEqual(302, response.status_code)

        # Superuser
        user.is_superuser = True
        user.save()
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        self.assertTrue(user.is_superuser)
        session = self.c.session
        session['os_list'] = os_list
        session.save()
        response = self.c.post(url, data)
        self.assertEqual(302, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.c.logout()
        user.is_superuser = False
        user.save()

        # User without Permissions
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        self.assertFalse(user.is_superuser)
        session = self.c.session
        session['os_list'] = os_list
        session.save()
        response = self.c.post(url, data)
        self.assertEqual(403, response.status_code)
        self.assertTrue(response.context['message'])
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response, '403.html')
        self.c.logout()

        # User with Modify Permissions
        user.grant('modify', self.vm)
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        self.assertFalse(user.is_superuser)
        session = self.c.session
        session['os_list'] = os_list
        session.save()
        response = self.c.post(url, data)
        self.assertEqual(302, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        user.revoke_all(self.vm)
        self.c.logout()

        # User with Admin Permissions
        user.grant('admin', self.vm)
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        self.assertFalse(user.is_superuser)
        session = self.c.session
        session['os_list'] = os_list
        session.save()
        response = self.c.post(url, data)
        self.assertEqual(302, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        user.revoke_all(self.vm)
        self.c.logout()
Example #9
0
    def test_view_modify_confirm(self):
        """
        Test confirm page for modifying an instance
        """

        args = (self.cluster.slug, self.vm.hostname)
        url = '/cluster/%s/%s/edit/confirm' % args

        user = User(id=52, username='******')
        user.set_password('secret2')
        user.save()

        self.vm.owner = user.get_profile()
        self.vm.save()

        os_list = cluster_os_list(self.cluster)
        edit_form = dict(vcpus=2,
                         acpi=True,
                         disk_cache='default',
                         initrd_path='',
                         kernel_args='ro',
                         kvm_flag='',
                         mem_path='',
                         migration_downtime=30,
                         security_domain='',
                         security_model='none',
                         usb_mouse='',
                         use_chroot=False,
                         use_localtime=False,
                         vnc_bind_address='0.0.0.0',
                         vnc_tls=False,
                         vnc_x509_path='',
                         vnc_x509_verify=False,
                         memory=512,
                         os='image+debian-osgeo',
                         disk_type='paravirtual',
                         boot_order='disk',
                         nic_type='paravirtual',
                         nic_count=1,
                         nic_count_original=1,
                         nic_link_0='br0',
                         nic_mac_0='aa:bb:00:00:33:d2',
                         root_path='/dev/vda1',
                         kernel_path='/boot/vmlinuz-2.32.6-27-generic',
                         serial_console=True,
                         cdrom_image_path='')

        ## SESSION VARIABLES
        # Make sure session variables are set
        user.is_superuser = True
        user.save()
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        session = self.c.session
        # edit_form
        response = self.c.get(url)
        self.assertEqual(400, response.status_code)
        session['edit_form'] = edit_form
        session.save()
        response = self.c.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response,
                                'ganeti/virtual_machine/edit_confirm.html')

        #session['os_list'] = os_list
        #session.save()
        user.revoke_all(self.vm)
        user.is_superuser = False
        user.save()
        self.c.logout()

        ## GET
        # Anonymous User
        response = self.c.get(url)
        self.assertEqual(302, response.status_code)

        # User with Modify Permissions
        user.grant('modify', self.vm)
        self.assertFalse(user.is_superuser)
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        session = self.c.session
        session['edit_form'] = edit_form
        session['os_list'] = os_list
        session.save()
        response = self.c.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8',
                         response['content-type'])
        self.assertTemplateUsed(response,
                                'ganeti/virtual_machine/edit_confirm.html')
        user.revoke_all(self.vm)
        self.c.logout()

        # User with Admin Permissions
        user.grant('admin', self.vm)
        self.assertFalse(user.is_superuser)
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        session = self.c.session
        session['edit_form'] = edit_form
        session['os_list'] = os_list
        session.save()
        response = self.c.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response,
                                'ganeti/virtual_machine/edit_confirm.html')
        user.revoke_all(self.vm)
        self.c.logout()

        # Superuser
        user.is_superuser = True
        user.save()
        self.assertTrue(self.c.login(username=user.username,
                                     password='******'))
        session = self.c.session
        session['edit_form'] = edit_form
        session['os_list'] = os_list
        session.save()
        response = self.c.get(url)
        self.assertEqual(200, response.status_code)
        self.assertEqual('text/html; charset=utf-8', response['content-type'])
        self.assertTemplateUsed(response,
                                'ganeti/virtual_machine/edit_confirm.html')
        self.c.logout()
        user.is_superuser = False
        user.save()

        ## POST
        data = {'rapi_dict': json.dumps(edit_form)}
        # Anonymous User
        response = self.c.post(url, data)
        self.assertEqual(302, response.status_code)

        for i in ('cancel', 'edit', 'save', 'reboot'):
            data[i] = True

            # Superuser
            user.is_superuser = True
            user.save()
            self.assertTrue(self.c.login(username=user.username,
                                         password='******'))
            session = self.c.session
            session['edit_form'] = edit_form
            session['os_list'] = os_list
            session.save()
            self.assertTrue(user.is_superuser)
            response = self.c.post(url, data)
            self.assertEqual(302, response.status_code)
            self.assertEqual('text/html; charset=utf-8',
                             response['content-type'])
            self.c.logout()
            user.is_superuser = False
            user.save()

            # User without Permissions
            self.assertTrue(self.c.login(username=user.username,
                                         password='******'))
            self.assertFalse(user.is_superuser)
            response = self.c.post(url, data)
            self.assertEqual(403, response.status_code)
            self.assertTrue(response.context['message'])
            self.assertEqual('text/html; charset=utf-8',
                             response['content-type'])
            self.assertTemplateUsed(response, '403.html')
            self.c.logout()

            # User with Modify Permissions
            user.grant('modify', self.vm)
            user.grant('power', self.vm)
            self.assertTrue(self.c.login(username=user.username,
                                         password='******'))
            session = self.c.session
            session['edit_form'] = edit_form
            session['os_list'] = os_list
            session.save()
            self.assertFalse(user.is_superuser)
            response = self.c.post(url, data)
            self.assertEqual(302, response.status_code)
            self.assertEqual('text/html; charset=utf-8',
                             response['content-type'])
            user.revoke_all(self.vm)
            self.c.logout()

            # User with Admin Permissions
            user.grant('admin', self.vm)
            self.assertTrue(self.c.login(username=user.username,
                                         password='******'))
            session = self.c.session
            session['edit_form'] = edit_form
            session['os_list'] = os_list
            session.save()
            self.assertFalse(user.is_superuser)
            response = self.c.post(url, data)
            self.assertEqual(302, response.status_code)
            self.assertEqual('text/html; charset=utf-8',
                             response['content-type'])
            user.revoke_all(self.vm)
            self.c.logout()

            del data[i]
Example #10
0
    def __init__(self, vm, initial=None, *args, **kwargs):
        super(VirtualMachineForm, self).__init__(initial, *args, **kwargs)

        # Set owner on form
        try:
            self.owner
        except AttributeError:
            self.owner = vm.owner

        # Setup os choices
        os_list = cluster_os_list(vm.cluster)
        self.fields['os'].choices = os_list

        for field in self.always_required:
            self.fields[field].required = True
        # If the required property is set on a child class,
        #  require those form fields
        try:
            if self.required:
                for field in self.required:
                    self.fields[field].required = True
        except AttributeError:
            pass

        # Need to set initial values from vm.info as these are not saved
        #  per the vm model.
        if vm.info:
            info = vm.info
            hvparam = info['hvparams']
            # XXX Convert ram string since it comes out
            #  from ganeti as an int and the DataVolumeField does not like
            #  ints.
            self.fields['vcpus'].initial = info['beparams']['vcpus']
            self.fields['memory'].initial = str(info['beparams']['memory'])

            # always take the larger nic count.  this ensures that if nics are
            # being removed that they will be in the form as Nones
            self.nics = len(info['nic.links'])
            nic_count = int(initial.get('nic_count', 1)) if initial else 1
            nic_count = self.nics if self.nics > nic_count else nic_count
            self.fields['nic_count'].initial = nic_count
            self.nic_fields = xrange(nic_count)
            for i in xrange(nic_count):
                link = forms.CharField(label=_('NIC/%s Link' % i),
                                       max_length=255,
                                       required=True)
                self.fields['nic_link_%s' % i] = link
                mac = MACAddressField(label=_('NIC/%s Mac' % i), required=True)
                self.fields['nic_mac_%s' % i] = mac
                if i < self.nics:
                    mac.initial = info['nic.macs'][i]
                    link.initial = info['nic.links'][i]

            self.fields['os'].initial = info['os']

            try:
                if self.hvparam_fields:
                    for field in self.hvparam_fields:
                        self.fields[field].initial = hvparam.get(field)
            except AttributeError:
                pass
Example #11
0
    def __init__(self, user, *args, **kwargs):
        self.user = user
        initial = kwargs.get('initial', None)

        super(NewVirtualMachineForm, self).__init__(*args, **kwargs)

        # If data is not passed by initial kwarg (as in POST data)
        #   assign initial to self.data as self.data contains POST
        #   data.
        if initial is None:
            initial = self.data

        cluster = None
        if initial:
            if 'cluster' in initial and initial['cluster']:
                try:
                    cluster = Cluster.objects.get(pk=initial['cluster'])
                except Cluster.DoesNotExist:
                    # defer to clean function to return errors
                    pass

            # Load disks and nics. Prefer raw fields, but unpack from dicts
            # if the raw fields are not available.  This allows modify and
            # API calls to use a cleaner syntax
            if 'disks' in initial and not 'disk_count' in initial:
                disks = initial['disks']
                initial['disk_count'] = disk_count = len(disks)
                for i, disk in enumerate(disks):
                    initial['disk_size_%s' % i] = disk['size']
            else:
                disk_count = int(initial.get('disk_count', 1))
            if 'nics' in initial and not 'nic_count' in initial:
                nics = initial['nics']
                initial['nic_count'] = nic_count = len(nics)
                for i, disk in enumerate(nics):
                    initial['nic_mode_%s' % i] = disk['mode']
                    initial['nic_link_%s' % i] = disk['link']
            else:
                nic_count = int(initial.get('nic_count', 1))
        else:
            disk_count = 1
            nic_count = 1

        # Make sure vcpus is required for this form. Don't want to go through
        #  the trouble of overriding the model field.
        self.fields['vcpus'].required = True

        if cluster is not None and cluster.info is not None:
            # set choices based on selected cluster if given
            oslist = cluster_os_list(cluster)
            nodelist = [
                str(h)
                for h in cluster.nodes.values_list('hostname', flat=True)
            ]
            nodes = zip(nodelist, nodelist)
            nodes.insert(0, self.empty_field)
            oslist.insert(0, self.empty_field)
            self.fields['pnode'].choices = nodes
            self.fields['snode'].choices = nodes
            self.fields['os'].choices = oslist

            # must have at least two nodes to use drbd
            if len(nodes) == 2:
                self.fields['disk_template'].choices = self.templates_single

            hv = initial.get('hypervisor', None)
            if hv is not None:
                defaults = cluster_default_info(cluster, hv)
            else:
                defaults = cluster_default_info(cluster)
                hv = defaults['hypervisor']
            if defaults['iallocator'] != '':
                self.fields['iallocator'].initial = True
                self.fields['iallocator_hostname'] = forms.CharField(
                    initial=defaults['iallocator'],
                    required=False,
                    widget=forms.HiddenInput())
            self.fields['vcpus'].initial = defaults['vcpus']
            self.fields['memory'].initial = defaults['memory']
            self.fields['hypervisor'].choices = defaults['hypervisors']
            self.fields['hypervisor'].initial = hv
            self.create_nic_fields(nic_count, defaults)

            if hv == 'kvm':
                self.fields['serial_console'].initial = defaults[
                    'serial_console']

            # Set field choices and hypervisor
            if hv == 'kvm' or hv == 'xen-pvm':
                self.fields['root_path'].initial = defaults['root_path']
                self.fields['kernel_path'].initial = defaults['kernel_path']
            if hv == 'kvm' or hv == 'xen-hvm':
                self.fields['nic_type'].choices = defaults['nic_types']
                self.fields['disk_type'].choices = defaults['disk_types']
                self.fields['boot_order'].choices = defaults['boot_devices']

                self.fields['nic_type'].initial = defaults['nic_type']
                self.fields['disk_type'].initial = defaults['disk_type']
                self.fields['boot_order'].initial = defaults['boot_order']
            if hv == 'xen-pvm':
                for field in self.pvm_exclude_fields:
                    del self.fields[field]
        else:
            self.create_nic_fields(nic_count)

        self.create_disk_fields(disk_count)

        # set cluster choices based on the given owner
        if initial and 'owner' in initial and initial['owner']:
            try:
                self.owner = ClusterUser.objects.get(
                    pk=initial['owner']).cast()
            except ClusterUser.DoesNotExist:
                self.owner = None
        else:
            self.owner = None

        # Set up owner and cluster choices.
        if user.is_superuser:
            # Superusers may do whatever they like.
            self.fields['owner'].queryset = ClusterUser.objects.all()
            self.fields['cluster'].queryset = Cluster.objects.exclude(
                username_or_mtime)
        else:
            # Fill out owner choices. Remember, the list of owners is a list
            # of tuple(ClusterUser.id, label). If you put ids from other
            # Models into this, no magical correction will be applied and you
            # will assign permissions to the wrong owner; see #2007.
            owners = [(u'', u'---------')]
            for group in user.groups.all():
                owners.append((group.organization.id, group.name))
            if user.has_any_perms(Cluster, ['admin', 'create_vm'], False):
                profile = user.get_profile()
                owners.append((profile.id, profile.name))
            self.fields['owner'].choices = owners

            # Set cluster choices.  If an owner has been selected then filter
            # by the owner.  Otherwise show everything the user has access to
            # through themselves or any groups they are a member of
            if self.owner:
                q = self.owner.get_objects_any_perms(Cluster,
                                                     ['admin', 'create_vm'])
            else:
                q = user.get_objects_any_perms(Cluster, ['admin', 'create_vm'])
            self.fields['cluster'].queryset = q.exclude(username_or_mtime)
Example #12
0
    def __init__(self, *args, **kwargs):
        """
        Initialize VirtualMachineTemplateForm
        """
        cluster = None
        initial = kwargs.get('initial', None)
        disk_count = 0
        nic_count = 0
        user = kwargs.pop('user', None)

        super(VirtualMachineForm, self).__init__(*args, **kwargs)

        if not initial:
            initial = dict(self.data.items())

        if initial:
            if initial.get('cluster', None):
                try:
                    cluster = Cluster.objects.get(pk=initial['cluster'])
                except Cluster.DoesNotExist:
                    # defer to clean function to return errors
                    pass

            # Load disks and nics.
            if 'disks' in initial and not 'disk_count' in initial: 
                disks = initial['disks']
                disk_count = len(disks)
                self.create_disk_fields(disk_count)
                for i, disk in enumerate(disks):
                    self.fields['disk_size_%s' % i].initial = disk['size']
            else:
                disk_count = int(initial['disk_count'])
                self.create_disk_fields(disk_count)
                for i in xrange(disk_count):
                    self.fields['disk_size_%s' %i].initial = initial['disk_size_%s'%i]

            if 'nics' in initial:
                nics = initial['nics']
                nic_count = len(nics)
                self.create_nic_fields(nic_count)
                for i, nic in enumerate(nics):
                    self.fields['nic_mode_%s' % i].initial = nic['mode']
                    self.fields['nic_link_%s' % i].initial = nic['link']
            else:
                nic_count = int(initial['nic_count'])
                self.create_nic_fields(nic_count)
                for i in xrange(nic_count):
                    self.fields['nic_mode_%s' % i].initial = initial['nic_mode_%s'%i]
                    self.fields['nic_link_%s' % i].initial = initial['nic_link_%s'%i]

        if cluster and hasattr(cluster, 'info'):
            # Get choices based on hypervisor passed to the form.
            hv = initial.get('hypervisor', None)
            if hv:
                defaults = cluster_default_info(cluster, hv)
            else:
                defaults = cluster_default_info(cluster)
                hv = defaults['hypervisor']
            # Set field choices and hypervisor
            if hv == 'kvm' or hv == 'xen-hvm':
                self.fields['nic_type'].choices = defaults['nic_types']
                self.fields['disk_type'].choices = defaults['disk_types']
                self.fields['boot_order'].choices = defaults['boot_devices']

            # Set os choices
            oslist = cluster_os_list(cluster)
            oslist.insert(0, self.empty_field)
            self.fields['os'].choices = oslist

        # Set cluster choices
        if user.is_superuser:
            clusters = Cluster.objects.all()
        else:
            clusters = user.get_objects_any_perms(Cluster, ['admin','create_vm'])

        self.fields['cluster'].queryset = clusters

        # XXX Remove fields explicitly set in NewVirtualMachineForm
        #  Django ticket #8620
        for field in self.Meta.exclude:
            if field in self.fields.keys():
                del self.fields[field]
        for field in self.fields:
            if field not in self.Meta.required:
                self.fields[field].required = False
            else:
                self.fields[field].required = True
    def __init__(self, *args, **kwargs):
        """
        Initialize VirtualMachineTemplateForm
        """
        cluster = None
        disk_count = 1
        nic_count = 1
        initial = kwargs.get("initial", None)
        user = kwargs.pop("user", None)

        super(VirtualMachineForm, self).__init__(*args, **kwargs)

        if not initial:
            initial = dict(self.data.items())

        if initial:
            if initial.get("cluster", None):
                try:
                    cluster = Cluster.objects.get(pk=initial["cluster"])
                except Cluster.DoesNotExist:
                    # defer to clean function to return errors
                    pass

            # Load disks and nics.
            if "disks" in initial and not "disk_count" in initial:
                disks = initial["disks"]
                disk_count = len(disks)
                self.create_disk_fields(disk_count)
                for i, disk in enumerate(disks):
                    self.fields["disk_size_%s" % i].initial = disk["size"]
            else:
                disk_count = int(initial["disk_count"])
                self.create_disk_fields(disk_count)
                for i in xrange(disk_count):
                    self.fields["disk_size_%s" % i].initial = initial["disk_size_%s" % i]

            if "nics" in initial:
                nics = initial["nics"]
                nic_count = len(nics)
                self.create_nic_fields(nic_count)
                for i, nic in enumerate(nics):
                    self.fields["nic_mode_%s" % i].initial = nic["mode"]
                    self.fields["nic_link_%s" % i].initial = nic["link"]
            else:
                nic_count = int(initial["nic_count"])
                self.create_nic_fields(nic_count)
                for i in xrange(nic_count):
                    self.fields["nic_mode_%s" % i].initial = initial["nic_mode_%s" % i]
                    self.fields["nic_link_%s" % i].initial = initial["nic_link_%s" % i]

        if cluster and hasattr(cluster, "info"):
            # Get choices based on hypervisor passed to the form.
            hv = initial.get("hypervisor", None)
            if hv:
                defaults = cluster_default_info(cluster, hv)
            else:
                defaults = cluster_default_info(cluster)
                hv = defaults["hypervisor"]
            # Set field choices and hypervisor
            if hv == "kvm" or hv == "xen-hvm":
                self.fields["nic_type"].choices = defaults["nic_types"]
                self.fields["disk_type"].choices = defaults["disk_types"]
                self.fields["boot_order"].choices = defaults["boot_devices"]

            # Set os choices
            oslist = cluster_os_list(cluster)
            oslist.insert(0, self.empty_field)
            self.fields["os"].choices = oslist

        if not initial:
            self.create_disk_fields(disk_count)
            self.create_nic_fields(nic_count)

        # Set cluster choices
        if user.is_superuser:
            clusters = Cluster.objects.all()
        else:
            clusters = user.get_objects_any_perms(Cluster, ["admin", "create_vm"])

        self.fields["cluster"].queryset = clusters

        # XXX Remove fields explicitly set in NewVirtualMachineForm
        #  Django ticket #8620
        for field in self.Meta.exclude:
            if field in self.fields.keys():
                del self.fields[field]
        for field in self.fields:
            if field not in self.Meta.required:
                self.fields[field].required = False
            else:
                self.fields[field].required = True
    def __init__(self, *args, **kwargs):
        """
        Initialize VirtualMachineTemplateForm
        """
        cluster = None
        disk_count = 1
        nic_count = 1
        initial = kwargs.get('initial', None)
        user = kwargs.pop('user', None)

        super(VirtualMachineForm, self).__init__(*args, **kwargs)

        if not initial:
            initial = dict(self.data.items())

        if initial:
            if initial.get('cluster', None):
                try:
                    cluster = Cluster.objects.get(pk=initial['cluster'])
                except Cluster.DoesNotExist:
                    # defer to clean function to return errors
                    pass

            # Load disks and nics.
            if 'disks' in initial and not 'disk_count' in initial: 
                disks = initial['disks']
                disk_count = len(disks)
                self.create_disk_fields(disk_count)
                for i, disk in enumerate(disks):
                    self.fields['disk_size_%s' % i].initial = disk['size']
            else:
                disk_count = int(initial['disk_count'])
                self.create_disk_fields(disk_count)
                for i in xrange(disk_count):
                    self.fields['disk_size_%s' %i].initial = initial['disk_size_%s'%i]

            if 'nics' in initial:
                nics = initial['nics']
                nic_count = len(nics)
                self.create_nic_fields(nic_count)
                for i, nic in enumerate(nics):
                    self.fields['nic_mode_%s' % i].initial = nic['mode']
                    self.fields['nic_link_%s' % i].initial = nic['link']
            else:
                nic_count = int(initial['nic_count'])
                self.create_nic_fields(nic_count)
                for i in xrange(nic_count):
                    self.fields['nic_mode_%s' % i].initial = initial['nic_mode_%s'%i]
                    self.fields['nic_link_%s' % i].initial = initial['nic_link_%s'%i]

       
        if cluster and hasattr(cluster, 'info'):
            # Get choices based on hypervisor passed to the form.
            hv = initial.get('hypervisor', None)
            if hv:
                defaults = cluster_default_info(cluster, hv)
            else:
                defaults = cluster_default_info(cluster)
                hv = defaults['hypervisor']
            # Set field choices and hypervisor
            if hv == 'kvm' or hv == 'xen-hvm':
                self.fields['nic_type'].choices = defaults['nic_types']
                self.fields['disk_type'].choices = defaults['disk_types']
                self.fields['boot_order'].choices = defaults['boot_devices']

            # Set os choices
            oslist = cluster_os_list(cluster)
            oslist.insert(0, self.empty_field)
            self.fields['os'].choices = oslist
        
        if not initial:
            self.create_disk_fields(disk_count)
            self.create_nic_fields(nic_count)

        # Set cluster choices
        if user.is_superuser:
            clusters = Cluster.objects.all()
        else:
            clusters = user.get_objects_any_perms(Cluster, ['admin','create_vm'])

        self.fields['cluster'].queryset = clusters

        # XXX Remove fields explicitly set in NewVirtualMachineForm
        #  Django ticket #8620
        for field in self.Meta.exclude:
            if field in self.fields.keys():
                del self.fields[field]
        for field in self.fields:
            if field not in self.Meta.required:
                self.fields[field].required = False
            else:
                self.fields[field].required = True