예제 #1
0
    def __init__(self, instance, *args, **kwargs):
        super(ReplaceDisksForm, self).__init__(*args, **kwargs)
        self.instance = instance

        # set disk choices based on the instance
        disk_choices = [(i, 'disk/%s' % i)
                        for i, v in enumerate(instance.info['disk.sizes'])]
        self.fields['disks'].choices = disk_choices

        # set choices based on the instances cluster
        cluster = instance.cluster
        nodelist = [
            str(h) for h in cluster.nodes.values_list('hostname', flat=True)
        ]
        nodes = zip(nodelist, nodelist)
        nodes.insert(0, self.empty_field)
        self.fields['node'].choices = nodes

        defaults = cluster_default_info(cluster, get_hypervisor(instance))
        if defaults['iallocator'] != '':
            self.fields['iallocator'].initial = True
            self.fields['iallocator_hostname'] = forms.CharField(
                initial=defaults['iallocator'],
                required=False,
                widget=forms.HiddenInput())
예제 #2
0
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
    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),
    )
예제 #3
0
    def __init__(self, cluster, node, *args, **kwargs):
        super(EvacuateForm, self).__init__(*args, **kwargs)

        node_list = [str(h) for h in cluster.nodes.exclude(pk=node.pk)
                     .values_list('hostname', flat=True)]
        nodes = zip(node_list, node_list)
        nodes.insert(0, self.EMPTY_FIELD)
        self.fields['node'].choices = nodes

        defaults = cluster_default_info(cluster)
        if defaults['iallocator'] != '':
            self.fields['iallocator'].initial = True
            self.fields['iallocator_hostname'].initial = defaults['iallocator']
def cluster_defaults(request):
    """
    Ajax view for retrieving the default cluster options to be set
    on the NewVirtualMachineForm.
    """
    cluster_id = request.GET.get('cluster_id', None)
    hypervisor = request.GET.get('hypervisor', 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 permission to view the default cluster options'))

    content = json.dumps(cluster_default_info(cluster, hypervisor))
    return HttpResponse(content, mimetype='application/json')
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),
    )
예제 #6
0
파일: virtual_machine.py 프로젝트: bsu/GWM2
    def __init__(self, instance, *args, **kwargs):
        super(ReplaceDisksForm, self).__init__(*args, **kwargs)
        self.instance = instance

        # set disk choices based on the instance
        disk_choices = [(i, 'disk/%s' % i) for i,v in enumerate(instance.info['disk.sizes'])]
        self.fields['disks'].choices = disk_choices

        # set choices based on the instances cluster
        cluster = instance.cluster
        nodelist = [str(h) for h in cluster.nodes.values_list('hostname', flat=True)]
        nodes = zip(nodelist, nodelist)
        nodes.insert(0, self.empty_field)
        self.fields['node'].choices = nodes

        defaults = cluster_default_info(cluster, get_hypervisor(instance))
        if defaults['iallocator'] != '' :
            self.fields['iallocator'].initial = True
            self.fields['iallocator_hostname'] = forms.CharField(
                                    initial=defaults['iallocator'],
                                    required=False,
                                    widget = forms.HiddenInput())
예제 #7
0
파일: virtual_machine.py 프로젝트: bsu/GWM2
    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
예제 #8
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)
예제 #9
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 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
예제 #11
0
    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
예제 #12
0
    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