Example #1
0
File: create.py Project: bsu/GWM2
 def test_no_nics(self):
     """
     test vm with no networking
     """
     self.data['nic_count'] = 0
     user.grant('create_vm', cluster)
     form = NewVirtualMachineForm(user, self.data)
     self.assertTrue(form.is_valid())
Example #2
0
File: create.py Project: bsu/GWM2
 def test_multiple_disks_missing_size(self):
     """
     tests submitting multiple disks, and that one is missing disk_size
     """
     self.data['disk_count'] = 2
     user.grant('create_vm', cluster)
     form = NewVirtualMachineForm(user, self.data)
     self.assertFalse(form.is_valid())
Example #3
0
 def test_no_disks(self):
     """
     test that diskless allows no disks
     """
     self.data['disk_count'] = 0
     self.user.grant('create_vm', self.cluster)
     form = NewVirtualMachineForm(self.user, self.data)
     self.assertTrue(form.is_valid())
Example #4
0
File: create.py Project: bsu/GWM2
 def test_no_disks(self):
     """
     test that diskless allows no disks
     """
     self.data['disk_count'] = 0
     user.grant('create_vm', cluster)
     form = NewVirtualMachineForm(user, self.data)
     self.assertTrue(form.is_valid())
Example #5
0
 def test_no_nics(self):
     """
     test vm with no networking
     """
     self.data['nic_count'] = 0
     self.user.grant('create_vm', self.cluster)
     form = NewVirtualMachineForm(self.user, self.data)
     self.assertTrue(form.is_valid())
Example #6
0
 def test_multiple_disks_missing_size(self):
     """
     tests submitting multiple disks, and that one is missing disk_size
     """
     self.data['disk_count'] = 2
     self.user.grant('create_vm', self.cluster)
     form = NewVirtualMachineForm(self.user, self.data)
     self.assertFalse(form.is_valid())
Example #7
0
 def test_spaces_in_hostname(self):
     """
     make sure validation fails if hostname has spaces
     """
     self.data['hostname'] = 'this has spaces.vm.hostname'
     self.user.grant('create_vm', self.cluster)
     form = NewVirtualMachineForm(self.user, self.data)
     self.assertFalse(form.is_valid())
Example #8
0
 def test_spaces_in_hostname(self):
     """
     make sure validation fails if hostname has spaces
     """
     self.data['hostname'] = 'this has spaces.vm.hostname'
     self.user.grant('create_vm', self.cluster)
     form = NewVirtualMachineForm(self.user, self.data)
     self.assertFalse(form.is_valid())
Example #9
0
File: create.py Project: bsu/GWM2
    def test_invalid_cluster(self):
        """
        An invalid cluster causes a form error.
        """

        data = self.data
        data['cluster'] = -1
        form = NewVirtualMachineForm(user, data)
        self.assertFalse(form.is_valid())
Example #10
0
    def test_invalid_cluster(self):
        """
        An invalid cluster causes a form error.
        """

        data = self.data
        data['cluster'] = -1
        form = NewVirtualMachineForm(self.user, data)
        self.assertFalse(form.is_valid())
Example #11
0
File: create.py Project: bsu/GWM2
 def test_multiple_disks_disk_size_calculation(self):
     """
     test that multiple disks are used in calculating total disk size
     """
     self.data['disk_count'] = 2
     self.data['disk_size_1'] = 3836
     user.grant('create_vm', cluster)
     form = NewVirtualMachineForm(user, self.data)
     self.assertTrue(form.is_valid())
     self.assertEqual(4836, form.cleaned_data['disk_size'])
Example #12
0
 def test_multiple_disks_disk_size_calculation(self):
     """
     test that multiple disks are used in calculating total disk size
     """
     self.data['disk_count'] = 2
     self.data['disk_size_1'] = 3836
     self.user.grant('create_vm', self.cluster)
     form = NewVirtualMachineForm(self.user, self.data)
     self.assertTrue(form.is_valid())
     self.assertEqual(4836, form.cleaned_data['disk_size'])
Example #13
0
 def test_multiple_nics_missing_nic_mode(self):
     """
     tests submitting multiple nics, and that one is missing nic_mode
     """
     self.data['nic_count'] = 2
     self.data['nic_link_0'] = 'br0'
     self.data['nic_link_1'] = 'br1'
     self.user.grant('create_vm', self.cluster)
     form = NewVirtualMachineForm(self.user, self.data)
     self.assertFalse(form.is_valid())
Example #14
0
File: create.py Project: bsu/GWM2
 def test_multiple_nics_missing_nic_mode(self):
     """
     tests submitting multiple nics, and that one is missing nic_mode
     """
     self.data['nic_count'] = 2
     self.data['nic_link_0'] = 'br0'
     self.data['nic_link_1'] = 'br1'
     user.grant('create_vm', cluster)
     form = NewVirtualMachineForm(user, self.data)
     self.assertFalse(form.is_valid())
Example #15
0
    def test_cluster_init(self):
        """
        Tests initializing a form with a Cluster

        Verifies:
            * cluster choices are set correctly
            * node choices are set correctly
        """

        # no cluster
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([(u'', u'---------')], form.fields['pnode'].choices)
        self.assertEqual([(u'', u'---------')], form.fields['snode'].choices)
        self.assertEqual([(u'', u'---------')], form.fields['os'].choices)

        # cluster from initial data
        form = NewVirtualMachineForm(self.user, {'cluster': self.cluster0.id})
        self.assertEqual(
            set([(u'', u'---------'),
                 (u'gtest1.example.bak', u'gtest1.example.bak'),
                 (u'gtest2.example.bak', u'gtest2.example.bak'),
                 (u'gtest3.example.bak', u'gtest3.example.bak')]),
            set(form.fields['pnode'].choices))
        self.assertEqual(
            set([(u'', u'---------'),
                 (u'gtest1.example.bak', u'gtest1.example.bak'),
                 (u'gtest2.example.bak', u'gtest2.example.bak'),
                 (u'gtest3.example.bak', u'gtest3.example.bak')]),
            set(form.fields['snode'].choices))
        self.assertEqual(form.fields['os'].choices,
                         [(u'', u'---------'),
                          ('Image', [('image+debian-osgeo', 'Debian Osgeo'),
                                     ('image+ubuntu-lucid', 'Ubuntu Lucid')])])

        # cluster from initial data
        form = NewVirtualMachineForm(self.user, {'cluster': self.cluster0.id})
        self.assertEqual(
            set([(u'', u'---------'),
                 (u'gtest1.example.bak', u'gtest1.example.bak'),
                 (u'gtest2.example.bak', u'gtest2.example.bak'),
                 (u'gtest3.example.bak', u'gtest3.example.bak')]),
            set(form.fields['pnode'].choices))
        self.assertEqual(
            set([(u'', u'---------'),
                 (u'gtest1.example.bak', u'gtest1.example.bak'),
                 (u'gtest2.example.bak', u'gtest2.example.bak'),
                 (u'gtest3.example.bak', u'gtest3.example.bak')]),
            set(form.fields['snode'].choices))
        self.assertEqual(form.fields['os'].choices,
                         [(u'', u'---------'),
                          ('Image', [('image+debian-osgeo', 'Debian Osgeo'),
                                     ('image+ubuntu-lucid', 'Ubuntu Lucid')])])
Example #16
0
    def test_init_and_data_params(self):
        """
        Tests that passing initial does not trigger validation

        Verifies:
            * Passing data (arg[0]) will trigger validation
            * Passing initial will not trigger validation
        """
        form = NewVirtualMachineForm(self.user, initial={})
        self.assertEqual({}, form.errors)

        form = NewVirtualMachineForm(self.user, {})
        self.assertNotEqual({}, form.errors)
Example #17
0
File: create.py Project: bsu/GWM2
    def test_iallocator(self):
        """
        The iallocator should be useable.
        """

        url = '/vm/add/%s'
        data = self.data
        data['iallocator'] = True
        data['iallocator_hostname'] = "hail"

        # Login and grant user.
        user.grant('create_vm', cluster)
        form = NewVirtualMachineForm(user, data)
        self.assertTrue(form.is_valid())
Example #18
0
    def test_wrong_cluster(self):
        """
        A cluster the user isn't authorized for causes a form error.
        """

        self.cluster1 = Cluster(hostname='test2.example.bak', slug='OSL_TEST2')
        self.cluster1.save()
        data = self.data
        data['cluster'] = self.cluster.id
        self.user.grant('create_vm', self.cluster1)
        self.user.is_superuser = False
        self.user.save()
        form = NewVirtualMachineForm(self.user, data)
        self.assertFalse(form.is_valid())
Example #19
0
File: create.py Project: bsu/GWM2
    def test_data_disk_quota_exceeded(self):
        """
        Disk quotas, when enabled, should cause form errors when exceeded.
        """

        data = self.data
        data['disk_size_0'] = 4000

        # Login and grant user.
        user.grant('create_vm', cluster)
        cluster.set_quota(user.get_profile(), dict(ram=1000, disk=2000, virtual_cpus=10))

        form = NewVirtualMachineForm(user, data)
        self.assertFalse(form.is_valid())
Example #20
0
File: create.py Project: bsu/GWM2
    def test_ram_quota_exceeded(self):
        """
        RAM quotas should cause form errors when exceeded.
        """

        data = self.data
        data['memory'] = 2048

        # Login and grant user.
        user.grant('create_vm', cluster)

        cluster.set_quota(user.get_profile(), dict(ram=1000, disk=2000, virtual_cpus=10))
        form = NewVirtualMachineForm(user, data)
        self.assertFalse(form.is_valid())
Example #21
0
    def test_iallocator(self):
        """
        The iallocator should be useable.
        """

        url = '/vm/add/%s'
        data = self.data
        data['iallocator'] = True
        data['iallocator_hostname'] = "hail"

        # Login and grant user.
        self.user.grant('create_vm', self.cluster)
        form = NewVirtualMachineForm(self.user, data)
        self.assertTrue(form.is_valid())
Example #22
0
File: create.py Project: bsu/GWM2
    def test_wrong_cluster(self):
        """
        A cluster the user isn't authorized for causes a form error.
        """

        cluster1 = Cluster(hostname='test2.osuosl.bak', slug='OSL_TEST2')
        cluster1.save()
        data = self.data
        data['cluster'] = cluster.id
        user.grant('create_vm', cluster1)
        user.is_superuser = False
        user.save()
        form = NewVirtualMachineForm(user, data)
        self.assertFalse(form.is_valid())
Example #23
0
File: create.py Project: bsu/GWM2
    def test_invalid_owner(self):
        """
        Obviously bogus owners should cause form errors.
        """
        url = '/vm/add/%s'
        data = self.data
        data['owner'] = -1

        # Login and grant user.
        self.assertTrue(c.login(username=user.username, password='******'))
        user.grant('create_vm', cluster)

        form = NewVirtualMachineForm(user, data)
        self.assertFalse(form.is_valid())
Example #24
0
    def test_data_disk_quota_exceeded(self):
        """
        Disk quotas, when enabled, should cause form errors when exceeded.
        """

        data = self.data
        data['disk_size_0'] = 4000

        # Login and grant user.
        self.user.grant('create_vm', self.cluster)
        self.cluster.set_quota(self.user.get_profile(),
                               dict(ram=1000, disk=2000, virtual_cpus=10))

        form = NewVirtualMachineForm(self.user, data)
        self.assertFalse(form.is_valid())
Example #25
0
    def test_ram_quota_exceeded(self):
        """
        RAM quotas should cause form errors when exceeded.
        """

        data = self.data
        data['memory'] = 2048

        # Login and grant user.
        self.user.grant('create_vm', self.cluster)

        self.cluster.set_quota(self.user.get_profile(),
                               dict(ram=1000, disk=2000, virtual_cpus=10))
        form = NewVirtualMachineForm(self.user, data)
        self.assertFalse(form.is_valid())
Example #26
0
    def test_invalid_owner(self):
        """
        Obviously bogus owners should cause form errors.
        """
        url = '/vm/add/%s'
        data = self.data
        data['owner'] = -1

        # Login and grant user.
        self.assertTrue(
            self.c.login(username=self.user.username, password='******'))
        self.user.grant('create_vm', self.cluster)

        form = NewVirtualMachineForm(self.user, data)
        self.assertFalse(form.is_valid())
Example #27
0
File: create.py Project: bsu/GWM2
    def test_data_cpu_quota_exceeded(self):
        """
        You may not emulate NUMA systems that exceed your quota.

        XXX should we also test more reasonable CPU limits?
        """

        data = self.data
        data['vcpus'] = 200

        # Login and grant user.
        user.grant('create_vm', cluster)
        cluster.set_quota(user.get_profile(), dict(ram=1000, disk=2000, virtual_cpus=10))

        form = NewVirtualMachineForm(user, data)
        self.assertFalse(form.is_valid())
Example #28
0
 def test_default_nics(self):
     self.user.grant('admin', self.cluster0)
     form = NewVirtualMachineForm(self.user)
     self.assertTrue('nic_mode_0' in form.fields)
     self.assertFalse('nic_mode_1' in form.fields)
     self.assertTrue('nic_link_0' in form.fields)
     self.assertFalse('nic_link_1' in form.fields)
Example #29
0
 def test_multiple_nics(self):
     self.user.grant('admin', self.cluster0)
     form = NewVirtualMachineForm(self.user, dict(nic_count=2))
     self.assertTrue('nic_mode_0' in form.fields)
     self.assertTrue('nic_mode_1' in form.fields)
     self.assertTrue('nic_link_0' in form.fields)
     self.assertTrue('nic_link_1' in form.fields)
Example #30
0
    def test_data_cpu_quota_exceeded(self):
        """
        You may not emulate NUMA systems that exceed your quota.

        XXX should we also test more reasonable CPU limits?
        """

        data = self.data
        data['vcpus'] = 200

        # Login and grant user.
        self.user.grant('create_vm', self.cluster)
        self.cluster.set_quota(self.user.get_profile(),
                               dict(ram=1000, disk=2000, virtual_cpus=10))

        form = NewVirtualMachineForm(self.user, data)
        self.assertFalse(form.is_valid())
Example #31
0
File: create.py Project: bsu/GWM2
    def test_required_keys(self):
        """
        If any of these keys are missing from the form data, a form error
        should occur.
        """

        data = self.data

        # grant user.
        user.grant('create_vm', cluster)

        for prop in ['cluster', 'hostname', 'disk_size_0', 'disk_type',
                     'nic_type', 'nic_mode_0', 'vcpus', 'pnode', 'os',
                     'disk_template', 'boot_order']:
            data_ = data.copy()
            del data_[prop]
            form = NewVirtualMachineForm(user, data_)
            self.assertFalse(form.is_valid(), prop)
Example #32
0
File: create.py Project: bsu/GWM2
    def test_iallocator_missing(self):
        """
        Enabling the iallocator without actually specifying which iallocator
        to run should cause a form error.
        """

        url = '/vm/add/%s'
        data = self.data
        data['iallocator'] = True

        # Login and grant user.
        user.grant('create_vm', cluster)
        user.get_profile()
        cluster.set_quota(user.get_profile(), dict(ram=1000, disk=2000, virtual_cpus=10))

        user.grant('create_vm', cluster)
        form = NewVirtualMachineForm(user, data)
        self.assertFalse(form.is_valid())
Example #33
0
def create_instance_from_template(request, cluster_slug, template):
    """
    View to create a new instance from a given template.
      Post method is handled by virtual_machine create view.
    """
    user = request.user
    if cluster_slug:
        cluster = get_object_or_404(Cluster, slug=cluster_slug)
        if not (
            user.is_superuser or
            user.has_perm('admin', cluster) or
            user.has_perm('create_vm', cluster)
            ):
            raise Http403(NO_PRIVS)

    vm_template = get_object_or_404(VirtualMachineTemplate,
                                    template_name=template,
                                    cluster__slug=cluster_slug)

    # Work with vm_template vars here
    initial = dict(
        cluster=vm_template.cluster_id,
    )
    initial.update(vars(vm_template))

    # nics and disks need to be replaced by expected
    #  form fields of disk_size_#, nic_mode_#, and nic_link_#
    ignore_fields = ('disks', 'nics', '_state',
        'description')
    for field in ignore_fields:
        del initial[field]

    # Initialize mutliple disks
    initial['disk_count'] = len(vm_template.disks)
    if initial['disk_count'] == 0:
        initial['disk_count'] = 1
    for i,disk in enumerate(vm_template.disks):
        initial['disk_size_%s'%i] = disk['size']

    # initialize multiple nics
    initial['nic_count'] = len(vm_template.nics)
    if initial['nic_count'] == 0:
        initial['nic_count'] = 1
    for i,nic in enumerate(vm_template.nics):
        initial['nic_mode_%s'%i] = nic['mode']
        initial['nic_link_%s'%i] = nic['link']

    form = NewVirtualMachineForm(user, initial=initial)
    cluster_defaults = {} #cluster_default_info(cluster)

    return render_to_response('ganeti/virtual_machine/create.html', {
        'form':form,
        'cluster_defaults':json.dumps(cluster_defaults),
        },
        context_instance = RequestContext(request)
    )
Example #34
0
    def test_iallocator_missing(self):
        """
        Enabling the iallocator without actually specifying which iallocator
        to run should cause a form error.
        """

        url = '/vm/add/%s'
        data = self.data
        data['iallocator'] = True

        # Login and grant user.
        self.user.grant('create_vm', self.cluster)
        self.user.get_profile()
        self.cluster.set_quota(self.user.get_profile(),
                               dict(ram=1000, disk=2000, virtual_cpus=10))

        self.user.grant('create_vm', self.cluster)
        form = NewVirtualMachineForm(self.user, data)
        self.assertFalse(form.is_valid())
Example #35
0
    def test_multiple_disks_from_dict(self):
        self.user.grant('admin', self.cluster0)
        initial = dict(disks=[dict(size=123), dict(size=456)])
        form = NewVirtualMachineForm(self.user, initial)
        self.assertTrue('disk_size_0' in form.fields)
        self.assertTrue('disk_size_1' in form.fields)

        data = form.data
        self.assertEqual(2, data['disk_count'])
        self.assertEqual(123, data['disk_size_0'])
        self.assertEqual(456, data['disk_size_1'])
Example #36
0
    def test_required_keys(self):
        """
        If any of these keys are missing from the form data, a form error
        should occur.
        """

        data = self.data

        # grant user.
        self.user.grant('create_vm', self.cluster)

        for prop in [
                'cluster', 'hostname', 'disk_size_0', 'disk_type', 'nic_type',
                'nic_mode_0', 'vcpus', 'pnode', 'os', 'disk_template',
                'boot_order'
        ]:
            data_ = data.copy()
            del data_[prop]
            form = NewVirtualMachineForm(self.user, data_)
            self.assertFalse(form.is_valid(), prop)
Example #37
0
 def test_default_choices(self):
     """
     Test that ChoiceFields have the correct default options
     """
     form = NewVirtualMachineForm(self.user)
     self.assertEqual([(u'', u'---------')],
                      form.fields['nic_type'].choices)
     self.assertEqual([(u'', u'---------'), (u'routed', u'routed'),
                       (u'bridged', u'bridged')],
                      form.fields['nic_mode_0'].choices)
     self.assertEqual([(u'', u'---------')],
                      form.fields['boot_order'].choices)
     self.assertEqual([(u'', u'---------'), (u'plain', u'plain'),
                       (u'drbd', u'drbd'), (u'file', u'file'),
                       (u'diskless', u'diskless')],
                      form.fields['disk_template'].choices)
Example #38
0
    def test_multiple_nics_from_dict(self):
        self.user.grant('admin', self.cluster0)
        initial = dict(
            nics=[dict(mode=123, link='br0'),
                  dict(mode=456, link='br1')])
        form = NewVirtualMachineForm(self.user, initial)
        self.assertTrue('nic_mode_0' in form.fields)
        self.assertTrue('nic_mode_1' in form.fields)
        self.assertTrue('nic_link_0' in form.fields)
        self.assertTrue('nic_link_1' in form.fields)

        data = form.data
        self.assertEqual(2, data['nic_count'])
        self.assertEqual(123, data['nic_mode_0'])
        self.assertEqual(456, data['nic_mode_1'])
        self.assertEqual('br0', data['nic_link_0'])
        self.assertEqual('br1', data['nic_link_1'])
def recover_failed_deploy(request, cluster_slug, instance):
    """
    Loads a vm that failed to deploy back into the edit form
    """
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    user = request.user
    if not (user.is_superuser or user.has_any_perms(vm, ['admin','modify']) \
        or user.has_perm('admin', cluster)):
        raise Http403(_('You do not have permissions to edit \
            this virtual machine'))

    # if there is no template, we can't recover.  redirect back to the detail
    # page.  its likely that this vm was already fixed
    if not vm.template_id:
        return HttpResponseRedirect(reverse('instance-detail', \
                                            args=[cluster_slug, instance]))

    # create initial data - load this from the template.  Not all properties
    # can be copied directly, some need to be copied explicitly due to naming
    # conflicts.
    initial = {'hostname':instance}
    for k,v in vm.template.__dict__.items():
        if v is not None and v != '':
            initial[k] = v
    initial['cluster'] = vm.template.cluster_id
    initial['pnode'] = vm.template.pnode
    initial['owner'] = vm.owner_id

    if "disks" in initial:
        for i, disk in enumerate(initial['disks']):
            initial['disk_size_%s' % i] = "%dMB" % disk["size"]

    if "nics" in initial:
        for i, nic in enumerate(initial['nics']):
            initial['nic_link_%s' % i] = nic['link']
            initial['nic_mode_%s' % i] = nic['mode']

    form = NewVirtualMachineForm(request.user, initial=initial)
    cluster_defaults = cluster_default_info(cluster)

    return render_to_response('ganeti/virtual_machine/create.html',
        {'form': form, 'cluster_defaults':json.dumps(cluster_defaults)},
        context_instance=RequestContext(request),
    )
Example #40
0
 def test_multiple_disks(self):
     self.user.grant('admin', self.cluster0)
     form = NewVirtualMachineForm(self.user, dict(disk_count=2))
     self.assertTrue('disk_size_0' in form.fields)
     self.assertTrue('disk_size_1' in form.fields)
def create(request, cluster_slug=None):
    """
    Create a new instance
        Store in DB and
        Create on given cluster
    """
    user = request.user
    if not(user.is_superuser or user.has_any_perms(Cluster, ['admin', 'create_vm'])):
        raise Http403(
            _('You do not have permission to create virtual machines'))

    if cluster_slug is not None:
        cluster = get_object_or_404(Cluster, slug=cluster_slug)
    else:
        cluster = None

    if request.method == 'POST':
        form = NewVirtualMachineForm(user, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            start = data.get('start')
            no_install = data.get('no_install')
            owner = data.get('owner')
            grantee = data.get('grantee')
            cluster = data.get('cluster')
            hostname = data.get('hostname')
            disk_template = data.get('disk_template')
            # Default to not pass in pnode and snode
            #  since these will be set if the form is correct
            pnode = None
            snode = None
            os = data.get('os')
            name_check = data.get('name_check')
            iallocator = data.get('iallocator')
            # Hidden fields
            iallocator_hostname = None
            if 'iallocator_hostname' in data:
                iallocator_hostname = data.get('iallocator_hostname')
            # BEPARAMS
            vcpus = data.get('vcpus')
            disks = data.get('disks')
            disk_size = data.get('disk_size')
            nics = data.get('nics')
            memory = data.get('memory')
            # If iallocator was not checked do not pass in the iallocator
            #  name. If iallocator was checked don't pass snode,pnode.
            if not iallocator:
                iallocator_hostname = None
                pnode = data.get('pnode')

            # If drbd is being used assign the secondary node
            if disk_template == 'drbd' and pnode is not None:
                snode = data.get('snode')

            # Create dictionary of only parameters supposed to be in hvparams
            hv = data.get('hypervisor')
            hvparams = {}
            hvparam_fields = ()

            if hv == 'xen-pvm':
                hvparam_fields = ('kernel_path', 'root_path')
            elif hv == 'xen-hvm':
                hvparam_fields = (
                    'boot_order',
                    'disk_type',
                    'nic_type',
                    'cdrom_image_path',
                )
            elif hv == 'kvm':
                hvparam_fields = [
                    'kernel_path',
                    'root_path',
                    'serial_console',
                    'boot_order',
                    'disk_type',
                    'cdrom_image_path',
                    'nic_type',
                ]

                # Check before adding cdrom2; see #11655.
                if has_cdrom2(cluster):
                    hvparam_fields.append('cdrom2_image_path')

                # Force cdrom disk type to IDE; see #9297.
                hvparams['cdrom_disk_type'] = 'ide'

            for field in hvparam_fields:
                hvparams[field] = data[field]

            # XXX attempt to load the virtual machine.  This ensure that if
            # there was a previous vm with the same hostname, but had not
            # successfully been deleted, then it will be deleted now
            try:
                VirtualMachine.objects.get(cluster=cluster, hostname=hostname)
            except VirtualMachine.DoesNotExist:
                pass

            try:
                job_id = cluster.rapi.CreateInstance('create', hostname,
                        disk_template,
                        disks,nics,
                        no_install=no_install,
                        start=start, os=os,
                        pnode=pnode, snode=snode,
                        name_check=name_check, ip_check=name_check,
                        iallocator=iallocator_hostname,
                        hypervisor=hv,
                        hvparams=hvparams,
                        beparams={"memory": memory, "vcpus":vcpus})
            except GanetiApiError, e:
                msg = '%s: %s' % (_('Error creating virtual machine on this cluster'),e)
                form._errors["cluster"] = form.error_class([msg])
            else:
                # Check for a vm recovery, If it is not found then
                if 'vm_recovery' in data:
                    vm = data['vm_recovery']
                    vm_template = vm.template
                else:
                    vm_template = VirtualMachineTemplate()
                    vm = VirtualMachine(owner=owner)

                vm.cluster = cluster
                vm.hostname = hostname
                vm.ram = memory
                vm.virtual_cpus = vcpus
                vm.disk_size = disk_size

                # save temporary template
                # XXX copy each property in data. Avoids errors from properties
                # that don't exist on the model
                for k,v in data.items():
                    setattr(vm_template, k, v)
                vm_template.save()

                vm.template = vm_template
                vm.ignore_cache = True

                # Do a dance to get the VM and the job referencing each other.
                vm.save()
                job = Job.objects.create(job_id=job_id, obj=vm, cluster=cluster)
                job.save()
                vm.last_job = job
                vm.save()

                # grant admin permissions to the owner.  Only do this for new
                # VMs.  otherwise we run the risk of granting perms to a
                # different owner.  We should be preventing that elsewhere, but
                # lets be extra careful since this check is cheap.
                if 'vm_recovery' in data:
                    log_action('VM_RECOVER', user, vm, job)
                else:
                    grantee.grant('admin', vm)
                    log_action('CREATE', user, vm)

                return HttpResponseRedirect(
                reverse('instance-detail', args=[cluster.slug, vm.hostname]))

        cluster_defaults = {}
        if 'cluster' in request.POST and request.POST['cluster'] != '':
            try:
                cluster =  Cluster.objects.get(pk=request.POST['cluster'])
                if cluster.info:
                    cluster_defaults = cluster_default_info(cluster)
            except Cluster.DoesNotExist:
                pass
Example #42
0
    def test_cluster_choices_init(self):
        """
        Tests that cluster choices are based on User permissions

        Verifies:
            * superusers have all Clusters as choices
            * if owner is set, only display clusters the owner has permissions
              directly on.  This includes both users and groups
            * if no owner is set, choices include clusters that the user has
              permission directly on, or through a group
        """

        # no owner, no permissions
        form = NewVirtualMachineForm(self.user)
        self.assertEqual(set([(u'', u'---------')]),
                         set(form.fields['cluster'].choices))

        # no owner, group and direct permissions
        self.user.grant('admin', self.cluster0)
        self.user.grant('create_vm', self.cluster1)
        self.group.grant('admin', self.cluster2)
        self.group.user_set.add(self.user)
        self.assertEqual(
            set([(u'', u'---------'), (self.cluster0.pk, u'test0'),
                 (self.cluster1.pk, u'test1'), (self.cluster2.pk, u'test2')]),
            set(form.fields['cluster'].choices))
        self.user.revoke_all(self.cluster0)
        self.user.revoke_all(self.cluster1)
        self.group.revoke_all(self.cluster2)

        # owner, user with no choices
        form = NewVirtualMachineForm(
            self.user, initial={'owner': self.user.get_profile().id})
        self.assertEqual(set([(u'', u'---------')]),
                         set(form.fields['cluster'].choices))

        # owner, user with choices
        self.user.grant('admin', self.cluster0)
        self.user.grant('create_vm', self.cluster1)
        form = NewVirtualMachineForm(
            self.user, initial={'owner': self.user.get_profile().id})
        self.assertEqual(
            set([(u'', u'---------'), (self.cluster0.pk, u'test0'),
                 (self.cluster1.pk, u'test1')]),
            set(form.fields['cluster'].choices))

        # owner, group with no choices
        form = NewVirtualMachineForm(
            self.user, initial={'owner': self.group.organization.id})
        self.assertEqual(set([(u'', u'---------')]),
                         set(form.fields['cluster'].choices))

        # owner, group with choices
        self.group.grant('admin', self.cluster2)
        self.group.grant('create_vm', self.cluster3)
        form = NewVirtualMachineForm(
            self.user, initial={'owner': self.group.organization.id})
        self.assertEqual(
            set([(u'', u'---------'), (self.cluster2.pk, u'test2'),
                 (self.cluster3.pk, u'test3')]),
            set(form.fields['cluster'].choices))

        # user - superuser
        self.user.is_superuser = True
        self.user.save()
        form = NewVirtualMachineForm(
            self.user, initial={'owner': self.user.get_profile().id})
        self.assertEqual(
            set([(u'', u'---------'), (self.cluster0.pk, u'test0'),
                 (self.cluster1.pk, u'test1'), (self.cluster2.pk, u'test2'),
                 (self.cluster3.pk, u'test3')]),
            set(form.fields['cluster'].choices))

        # group - superuser
        form = NewVirtualMachineForm(
            self.user, initial={'owner': self.group.organization.id})
        self.assertEqual(
            set([(u'', u'---------'), (self.cluster0.pk, u'test0'),
                 (self.cluster1.pk, u'test1'), (self.cluster2.pk, u'test2'),
                 (self.cluster3.pk, u'test3')]),
            set(form.fields['cluster'].choices))
Example #43
0
    def test_owner_choices_init(self):
        """
        Tests that owner choices are set based on User permissions

        Verifies:
            * superusers have all clusterusers as choices
            * user receives themselves as a choice if they have perms
            * user receives all groups they are a member of
        """

        # user with no choices
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([(u'', u'---------')], form.fields['owner'].choices)

        # user with perms on self, no groups
        self.user.grant('admin', self.cluster0)
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([
            (u'', u'---------'),
            (self.user.profile.id, u'tester0'),
        ], form.fields['owner'].choices)
        self.user.set_perms(['create_vm'], self.cluster0)
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([
            (u'', u'---------'),
            (self.user.profile.id, u'tester0'),
        ], form.fields['owner'].choices)

        # user with perms on self and groups
        self.group.user_set.add(self.user)
        self.group.grant('admin', self.cluster0)
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([
            (u'', u'---------'),
            (self.group.organization.id, u'testing_group'),
            (self.user.profile.id, u'tester0'),
        ], form.fields['owner'].choices)
        self.user.revoke_all(self.cluster0)

        # user with no perms on self, but groups
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([
            (u'', u'---------'),
            (self.group.organization.id, u'testing_group'),
        ], form.fields['owner'].choices)
        self.group.set_perms(['create_vm'], self.cluster0)
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([
            (u'', u'---------'),
            (self.group.organization.id, u'testing_group'),
        ], form.fields['owner'].choices)
        self.group.revoke_all(self.cluster0)

        # superuser
        self.user.is_superuser = True
        self.user.save()
        form = NewVirtualMachineForm(self.user)
        self.assertEqual([
            (u'', u'---------'),
            (self.user.profile.id, u'tester0'),
            (self.user1.profile.id, u'tester1'),
            (self.group.organization.id, u'testing_group'),
        ], list(form.fields['owner'].choices))
Example #44
0
 def test_default_disks(self):
     self.user.grant('admin', self.cluster0)
     form = NewVirtualMachineForm(self.user)
     self.assertTrue('disk_size_0' in form.fields)
     self.assertFalse('disk_size_1' in form.fields)
                    log_action('CREATE', user, vm)

                return HttpResponseRedirect(
                reverse('instance-detail', args=[cluster.slug, vm.hostname]))

        cluster_defaults = {}
        if 'cluster' in request.POST and request.POST['cluster'] != '':
            try:
                cluster =  Cluster.objects.get(pk=request.POST['cluster'])
                if cluster.info:
                    cluster_defaults = cluster_default_info(cluster)
            except Cluster.DoesNotExist:
                pass

    elif request.method == 'GET':
        form = NewVirtualMachineForm(user)
        cluster_defaults = {}

    return render_to_response('ganeti/virtual_machine/create.html', {
        'form': form,
        'cluster_defaults':json.dumps(cluster_defaults)
        },
        context_instance=RequestContext(request),
    )


@login_required
def modify(request, cluster_slug, instance):
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    user = request.user