Пример #1
0
 def test_compare_bool_disabled(self):
     self.assertEqual(compare(True, False), "disabled")
Пример #2
0
 def test_compare_float_increased(self):
     self.assertEqual(compare(-34.0, 53.23),
                      "increased from -34.0 to 53.23")
Пример #3
0
 def test_compare_string_changed(self):
     self.assertEqual(compare("foo", "bar"), "changed from foo to bar")
Пример #4
0
 def test_compare_bool_enabled(self):
     self.assertEqual(compare(False, True), "enabled")
def modify_confirm(request, cluster_slug, instance):
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    hv = get_hypervisor(vm)
    if hv == 'kvm':
        hv_form = KvmModifyVirtualMachineForm
    elif hv == 'xen-pvm':
        hv_form = PvmModifyVirtualMachineForm
    elif hv == 'xen-hvm':
        hv_form = HvmModifyVirtualMachineForm
    else:
        hv_form = None
        # XXX no matter what, we're gonna call hv_form() and die. Let's do it
        # louder than usual. >:3
        msg = "Hey, guys, implementation error in views/vm.py:modify_confirm"
        raise RuntimeError(msg)

    user = request.user
    power = user.is_superuser or user.has_any_perms(vm, ['admin','power'])
    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 request.method == "POST":
        if 'edit' in request.POST:
            return HttpResponseRedirect(
                reverse("instance-modify",
                args=[cluster.slug, vm.hostname]))
        elif 'reboot' in request.POST or 'save' in request.POST:
            form = ModifyConfirmForm(request.POST)
            form.session = request.session
            form.owner = vm.owner
            form.vm = vm
            form.cluster = cluster

            if form.is_valid():
                data = form.cleaned_data
                rapi_dict = data['rapi_dict']
                nics = rapi_dict.pop('nics')
                vcpus = rapi_dict.pop('vcpus')
                memory = rapi_dict.pop('memory')
                os_name = rapi_dict.pop('os')
                job_id = cluster.rapi.ModifyInstance(instance,
                    nics=nics, os_name=os_name, hvparams=rapi_dict,
                    beparams={'vcpus':vcpus,'memory':memory}
                )
                # Create job and update message on virtual machine detail page
                job = Job.objects.create(job_id=job_id, obj=vm, cluster=cluster)
                VirtualMachine.objects.filter(id=vm.id).update(last_job=job,
                                                           ignore_cache=True)
                # log information about modifying this instance
                log_action('EDIT', user, vm)
                if 'reboot' in request.POST and vm.info['status'] == 'running':
                    if power:
                        # Reboot the vm
                        job = vm.reboot()
                        log_action('VM_REBOOT', user, vm, job)
                    else:
                        raise Http403(
                            _("Sorry, but you do not have permission to reboot this machine."))

                # Redirect to instance-detail
                return HttpResponseRedirect(
                    reverse("instance-detail", args=[cluster.slug, vm.hostname]))

        elif 'cancel' in request.POST:
            # Remove session variables.
            if 'edit_form' in request.session:
                del request.session['edit_form']
            # Redirect to instance-detail
            return HttpResponseRedirect(
                reverse("instance-detail", args=[cluster.slug, vm.hostname]))

    elif request.method == "GET":
        form = ModifyConfirmForm()

    session = request.session

    if not 'edit_form' in request.session:
        return HttpResponseBadRequest('Incorrect Session Data')

    data = session['edit_form']
    info = vm.info
    hvparams = info['hvparams']

    old_set = dict(
        memory=info['beparams']['memory'],
        vcpus=info['beparams']['vcpus'],
        os=info['os'],
    )

    nic_count = len(info['nic.links'])
    for i in xrange(nic_count):
        old_set['nic_link_%s' % i] = info['nic.links'][i]
        old_set['nic_mac_%s' % i] = info['nic.macs'][i]

    # Add hvparams to the old_set
    old_set.update(hvparams)

    instance_diff = {}
    fields = hv_form(vm, data).fields
    for key in data.keys():
        if key == 'memory':
            diff = compare(render_storage(old_set[key]),
                render_storage(data[key]))
        elif key == 'os':
            oses = os_prettify([old_set[key], data[key]])
            if len(oses) > 1:
                """
                XXX - Special case for a cluster with two different types of
                  optgroups (i.e. Image, Debootstrap).
                  The elements at 00 and 10:
                    The optgroups
                  The elements at 010 and 110:
                    Tuple containing the OS Name and OS value.
                  The elements at 0101 and 1101:
                    String containing the OS Name
                """
                oses[0][1][0] = list(oses[0][1][0])
                oses[1][1][0] = list(oses[1][1][0])
                oses[0][1][0][1] = '%s (%s)' % (oses[0][1][0][1], oses[0][0])
                oses[1][1][0][1] = '%s (%s)' % (oses[1][1][0][1], oses[1][0])
                oses = oses[0][1] + oses[1][1]
                diff = compare(oses[0][1], oses[1][1])
            else:
                oses = oses[0][1]
                diff = compare(oses[0][1], oses[1][1])
            #diff = compare(oses[0][1], oses[1][1])
        if key in ['nic_count','nic_count_original']:
            continue
        elif key not in old_set.keys():
            diff = ""
            instance_diff[fields[key].label] = _('Added')
        else:
            diff = compare(old_set[key], data[key])

        if diff != "":
            label = fields[key].label
            instance_diff[label] = diff

    # remove mac if it has not changed
    for i in xrange(nic_count):
        if fields['nic_mac_%s' % i].label not in instance_diff:
            del data['nic_mac_%s' % i]

    # Repopulate form with changed values
    form.fields['rapi_dict'] = CharField(widget=HiddenInput,
        initial=json.dumps(data))

    return render_to_response(
        'ganeti/virtual_machine/edit_confirm.html', {
        'cluster': cluster,
        'form': form,
        'instance': vm,
        'instance_diff': instance_diff,
        'power':power,
        },
        context_instance=RequestContext(request),
    )
Пример #6
0
 def test_compare_string_removed(self):
     self.assertEqual(compare("bar", ""), "removed")
Пример #7
0
 def test_compare_int_increased(self):
     self.assertEqual(compare(-4, 0), "increased from -4 to 0")
Пример #8
0
 def test_compare_int_decreased(self):
     self.assertEqual(compare(2, 0), "decreased from 2 to 0")
Пример #9
0
 def test_compare_float_increased(self):
     self.assertEqual(compare(-34.0, 53.23),
                      "increased from -34.0 to 53.23")
Пример #10
0
 def test_compare_float_decreased(self):
     self.assertEqual(compare(53.23, -34.0),
                      "decreased from 53.23 to -34.0")
Пример #11
0
 def test_compare_bool_disabled(self):
     self.assertEqual(compare(True, False), "disabled")
Пример #12
0
 def test_compare_bool_enabled(self):
     self.assertEqual(compare(False, True), "enabled")
Пример #13
0
 def test_compare_string_changed(self):
     self.assertEqual(compare("foo", "bar"), "changed from foo to bar")
Пример #14
0
 def test_compare_float_decreased(self):
     self.assertEqual(compare(53.23, -34.0),
                      "decreased from 53.23 to -34.0")
Пример #15
0
 def test_compare_int_decreased(self):
     self.assertEqual(compare(2, 0), "decreased from 2 to 0")
Пример #16
0
 def test_compare_int_increased(self):
     self.assertEqual(compare(-4, 0), "increased from -4 to 0")
Пример #17
0
 def test_compare_string_set(self):
     self.assertEqual(compare("", "foo"), "set to foo")
Пример #18
0
    def test_compare(self):
        """
        Tests compare utility function
        """
        string1 = "foo"
        string2 = "bar"
        string3 = ""
        int1 = 2
        int2 = 0
        int3 = -4
        float1 = 53.23
        float2 = -34.00
        bool1 = True
        bool2 = False

        stringRemoved = "removed"
        stringSet = "set to %s"
        stringChanged = "changed from %s to %s"
        boolEnabled = "enabled"
        boolDisabled = "disabled"
        numIncreased = "increased from %s to %s"
        numDecreased = "decreased from %s to %s"

        # String set
        result = compare(string3, string1)
        outcome = stringSet % string1
        self.assertEqual(result, outcome)

        # String removed
        result = compare(string2, string3)
        outcome = stringRemoved
        self.assertEqual(result, outcome)

        # String changed
        result = compare(string1, string2)
        outcome = stringChanged % (string1, string2)
        self.assertEqual(result, outcome)


        # Boolean enabled
        result = compare(bool2, bool1)
        outcome = boolEnabled
        self.assertEqual(result, outcome)

        # Boolean disabled
        result = compare(bool1, bool2)
        outcome = boolDisabled
        self.assertEqual(result, outcome)
    

        # Num increased
        result = compare(float2, float1)
        outcome = numIncreased % (float2, float1)
        self.assertEqual(result, outcome)

        result = compare(int3, int2)
        outcome = numIncreased % (int3, int2)
        self.assertEqual(result, outcome)

        # Num decreased
        result = compare(float1, float2)
        outcome = numDecreased % (float1, float2)
        self.assertEqual(result, outcome)

        result = compare(int1, int2)
        outcome = numDecreased % (int1, int2)
        self.assertEqual(result, outcome)
Пример #19
0
 def test_compare_string_removed(self):
     self.assertEqual(compare("bar", ""), "removed")
Пример #20
0
def modify_confirm(request, cluster_slug, instance):
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    hv = get_hypervisor(vm)
    if hv == 'kvm':
        hv_form = KvmModifyVirtualMachineForm
    elif hv == 'xen-pvm':
        hv_form = PvmModifyVirtualMachineForm
    elif hv == 'xen-hvm':
        hv_form = HvmModifyVirtualMachineForm
    else:
        hv_form = None
        # XXX no matter what, we're gonna call hv_form() and die. Let's do it
        # louder than usual. >:3
        msg = "Hey, guys, implementation error in views/vm.py:modify_confirm"
        raise RuntimeError(msg)

    user = request.user
    power = user.is_superuser or user.has_any_perms(vm, ['admin', 'power'])
    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 request.method == "POST":
        if 'edit' in request.POST:
            return HttpResponseRedirect(
                reverse("instance-modify",
                        args=[cluster.slug, vm.hostname]))
        elif 'reboot' in request.POST or 'save' in request.POST:
            form = ModifyConfirmForm(request.POST)
            form.session = request.session
            form.owner = vm.owner
            form.vm = vm
            form.cluster = cluster

            if form.is_valid():
                beparams = {}
                data = form.cleaned_data
                rapi_dict = data['rapi_dict']
                nics = rapi_dict.pop('nics')
                beparams['vcpus'] = rapi_dict.pop('vcpus')
                if has_balloonmem(cluster):
                    beparams['maxmem'] = rapi_dict.pop('maxmem')
                    beparams['minmem'] = rapi_dict.pop('minmem')
                else:
                    beparams['memroy'] = rapi_dict.pop('memory')
                os_name = rapi_dict.pop('os')
                job_id = cluster.rapi.ModifyInstance(
                    instance,
                    nics=nics,
                    os_name=os_name,
                    hvparams=rapi_dict,
                    beparams=beparams)
                # Create job and update message on virtual machine detail page
                job = Job.objects.create(job_id=job_id,
                                         obj=vm,
                                         cluster=cluster)
                VirtualMachine.objects \
                    .filter(id=vm.id).update(last_job=job, ignore_cache=True)
                # log information about modifying this instance
                log_action('EDIT', user, vm)
                if 'reboot' in request.POST and vm.info['status'] == 'running':
                    if power:
                        # Reboot the vm
                        job = vm.reboot()
                        log_action('VM_REBOOT', user, vm, job)
                    else:
                        raise Http403(
                            _("Sorry, but you do not have permission "
                              "to reboot this machine."))

                # Redirect to instance-detail
                return HttpResponseRedirect(
                    reverse("instance-detail",
                            args=[cluster.slug, vm.hostname]))

        elif 'cancel' in request.POST:
            # Remove session variables.
            if 'edit_form' in request.session:
                del request.session['edit_form']
            # Redirect to instance-detail
            return HttpResponseRedirect(
                reverse("instance-detail", args=[cluster.slug, vm.hostname]))

    elif request.method == "GET":
        form = ModifyConfirmForm()

    session = request.session

    if not 'edit_form' in request.session:
        return HttpResponseBadRequest('Incorrect Session Data')

    data = session['edit_form']
    info = vm.info
    hvparams = info['hvparams']

    old_set = dict(
        vcpus=info['beparams']['vcpus'],
        os=info['os'],
    )
    if has_balloonmem(cluster):
        old_set['maxmem'] = info['beparams']['maxmem']
        old_set['minmem'] = info['beparams']['minmem']
    else:
        old_set['memory'] = info['beparams']['memory']
    nic_count = len(info['nic.links'])
    for i in xrange(nic_count):
        old_set['nic_link_%s' % i] = info['nic.links'][i]
        old_set['nic_mac_%s' % i] = info['nic.macs'][i]

    # Add hvparams to the old_set
    old_set.update(hvparams)

    instance_diff = {}
    fields = hv_form(vm, data).fields
    for key in data.keys():
        if key in ['memory', 'maxmem', 'minmem']:
            diff = compare(render_storage(old_set[key]),
                           render_storage(data[key]))
        elif key == 'os':
            oses = os_prettify([old_set[key], data[key]])
            if len(oses) > 1:
                """
                XXX - Special case for a cluster with two different types of
                  optgroups (i.e. Image, Debootstrap).
                  The elements at 00 and 10:
                    The optgroups
                  The elements at 010 and 110:
                    Tuple containing the OS Name and OS value.
                  The elements at 0101 and 1101:
                    String containing the OS Name
                """
                oses[0][1][0] = list(oses[0][1][0])
                oses[1][1][0] = list(oses[1][1][0])
                oses[0][1][0][1] = '%s (%s)' % (oses[0][1][0][1], oses[0][0])
                oses[1][1][0][1] = '%s (%s)' % (oses[1][1][0][1], oses[1][0])
                oses = oses[0][1] + oses[1][1]
                diff = compare(oses[0][1], oses[1][1])
            else:
                oses = oses[0][1]
                diff = compare(oses[0][1], oses[1][1])
            #diff = compare(oses[0][1], oses[1][1])
        if key in ['nic_count', 'nic_count_original']:
            continue
        elif key not in old_set.keys():
            diff = ""
            instance_diff[fields[key].label] = _('Added')
        else:
            diff = compare(old_set[key], data[key])

        if diff != "":
            label = fields[key].label
            instance_diff[label] = diff

    # remove mac if it has not changed
    for i in xrange(nic_count):
        if fields['nic_mac_%s' % i].label not in instance_diff:
            del data['nic_mac_%s' % i]

    # Repopulate form with changed values
    form.fields['rapi_dict'] = CharField(widget=HiddenInput,
                                         initial=json.dumps(data))

    return render_to_response(
        'ganeti/virtual_machine/edit_confirm.html', {
        'cluster': cluster,
        'form': form,
        'instance': vm,
        'instance_diff': instance_diff,
        'power': power,
        },
        context_instance=RequestContext(request),
    )
Пример #21
0
 def test_compare_string_set(self):
     self.assertEqual(compare("", "foo"), "set to foo")