示例#1
0
文件: general.py 项目: bsu/GWM2
def used_resources(request, rest=False):
    """ view for returning used resources for a given cluster user """
    try:
        cluster_user_id = request.GET['id']
    except KeyError:
        return render_404(request, 'requested user was not found')
    cu = get_object_or_404(ClusterUser, pk=cluster_user_id)
    
    # must be a super user, the user in question, or a member of the group
    user = request.user
    if not user.is_superuser:
        user_type = ContentType.objects.get_for_model(Profile)
        if cu.real_type_id == user_type.pk:
            if not Profile.objects.filter(clusteruser_ptr=cu.pk, user=user)\
                .exists():
                return render_403(request, _('You are not authorized to view this page'))
        else:
            if not Organization.objects.filter(clusteruser_ptr=cu.pk, \
                                               group__user=user).exists():
                return render_403(request, _('You are not authorized to view this page'))
    
    resources = get_used_resources(cu.cast())
    if rest:
        return resources
    else:
        return render_to_response("ganeti/overview/used_resources.html", {
            'resources':resources
        }, context_instance=RequestContext(request))
示例#2
0
文件: node.py 项目: bsu/GWM2
def detail(request, cluster_slug, host, rest=False):
    """
    Renders a detail view for a Node
    """
    node, cluster = get_node_and_cluster_or_404(cluster_slug, host)
    
    user = request.user
    admin = True if user.is_superuser else user.has_perm('admin', cluster)
    modify = True if admin else user.has_perm('migrate', cluster)
    if not (admin or modify):
        return render_403(request, _("You do not have sufficient privileges"))

    if rest:
        return {'cluster':cluster,
        'node_count':cluster.nodes.all().count(),
        'node':node,
        'admin':admin,
        'modify':modify}
    else:
        return render_to_response("ganeti/node/detail.html", {
            'cluster':cluster,
            'node_count':cluster.nodes.all().count(),
            'node':node,
            'admin':admin,
            'modify':modify,
            },
            context_instance=RequestContext(request),
            )
示例#3
0
文件: node.py 项目: bsu/GWM2
def evacuate(request, cluster_slug, host):
    """
    view used for initiating a node evacuate job
    """
    node, cluster = get_node_and_cluster_or_404(cluster_slug, host)
    
    user = request.user
    if not (user.is_superuser or user.has_any_perms(cluster, ['admin','migrate'])):
        return render_403(request, _("You do not have sufficient privileges"))

    if request.method == 'POST':
        form = EvacuateForm(cluster, node, request.POST)
        if form.is_valid():
            try:
                data = form.cleaned_data
                evacuate_node = data['node']
                iallocator_hostname = data['iallocator_hostname']
                job = node.evacuate(iallocator_hostname, evacuate_node)
                job.refresh()
                msg = job.info

                # log information
                log_action('NODE_EVACUATE', user, node, job)

                return HttpResponse(json.dumps(msg), mimetype='application/json')
            except GanetiApiError, e:
                content = json.dumps({'__all__':[str(e)]})
        else:
            # error in form return ajax response
            content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')
示例#4
0
def shutdown(request, cluster_slug, instance, rest=False):
    vm = get_object_or_404(VirtualMachine, hostname=instance,
                           cluster__slug=cluster_slug)
    user = request.user

    if not (user.is_superuser or user.has_any_perms(vm, ['admin','power']) or
        user.has_perm('admin', vm.cluster)):
        if not rest:
            return render_403(request, _('You do not have permission to shut down this virtual machine'))
        else:
            return {"msg":'You do not have permission to shut down this virtual machine', 'code': 403}

    if (request.method == 'POST') | rest:
        try:
            job = vm.shutdown()
            job.refresh()
            msg = job.info

            # log information about stopping the machine
            log_action('VM_STOP', user, vm, job)
        except GanetiApiError, e:
            msg = {'__all__':[str(e)]}
        if (not rest):
            return HttpResponse(json.dumps(msg), mimetype='application/json')
        else:
            return {'msg':msg, 'code':200}
示例#5
0
def reboot(request, cluster_slug, instance, rest=False):
    vm = get_object_or_404(VirtualMachine, hostname=instance,
                           cluster__slug=cluster_slug)
    user = request.user
    if not (user.is_superuser or user.has_any_perms(vm, ['admin','power']) or
        user.has_perm('admin', vm.cluster)):

            if not rest:
                return render_403(request, _('You do not have permission to reboot this virtual machine'))
            else:
                return HttpResponseForbidden

    if request.method == 'POST':
        try:
            job = vm.reboot()
            job.refresh()
            msg = job.info

            # log information about restarting the machine
            log_action('VM_REBOOT', user, vm, job)
        except GanetiApiError, e:
            msg = {'__all__':[str(e)]}
        if not rest:
            return HttpResponse(json.dumps(msg), mimetype='application/json')
        else:
            return HttpAccepted
示例#6
0
文件: cluster.py 项目: bsu/GWM2
def object_log(request, cluster_slug):
    """ displays object log for this cluster """
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    user = request.user
    if not (user.is_superuser or user.has_perm('admin', cluster)):
        return render_403(request, _("You do not have sufficient privileges"))
    return list_for_object(request, cluster)
示例#7
0
def migrate(request, cluster_slug, instance):
    """
    view used for initiating a Node Migrate job
    """
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    user = request.user
    if not (user.is_superuser or user.has_any_perms(cluster, ['admin','migrate'])):
        return render_403(request, _("You do not have sufficient privileges"))

    if request.method == 'POST':
        form = MigrateForm(request.POST)
        if form.is_valid():
            try:
                job = vm.migrate(form.cleaned_data['mode'])
                job.refresh()
                content = json.dumps(job.info)

                # log information
                log_action('VM_MIGRATE', user, vm, job)
            except GanetiApiError, e:
                content = json.dumps({'__all__':[str(e)]})
        else:
            # error in form return ajax response
            content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')
示例#8
0
def reparent(request, cluster_slug, instance):
    """
    update a virtual machine to have a new owner
    """
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    user = request.user
    if not (user.is_superuser or user.has_perm('admin', cluster)):
        return render_403(request,
            _('You do not have permissions to change the owner of this virtual machine'))

    if request.method == 'POST':
        form = ChangeOwnerForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            vm.owner = data['owner']
            vm.save(force_update=True)

            # log information about creating the machine
            log_action('VM_MODIFY', user, vm)

            return HttpResponseRedirect(reverse('instance-detail', args=[cluster_slug, instance]))

    else:
        form = ChangeOwnerForm()

    return render_to_response(
        'ganeti/virtual_machine/reparent.html', {
        'cluster': cluster,
        'vm': vm,
        'form': form
        },
        context_instance=RequestContext(request),
    )
示例#9
0
文件: node.py 项目: bsu/GWM2
def role(request, cluster_slug, host):
    """
    view used for setting node role
    """
    node, cluster = get_node_and_cluster_or_404(cluster_slug, host)
    
    user = request.user
    if not (user.is_superuser or user.has_any_perms(cluster, ['admin','migrate'])):
        return render_403(request, _("You do not have sufficient privileges"))
    
    if request.method == 'POST':
        form = RoleForm(request.POST)
        if form.is_valid():
            try:
                job = node.set_role(form.cleaned_data['role'])
                job.refresh()
                msg = job.info

                # log information
                log_action('NODE_ROLE_CHANGE', user, node)
                return HttpResponse(json.dumps(msg), mimetype='application/json')
            except GanetiApiError, e:
                content = json.dumps({'__all__':[str(e)]})
        else:
            # error in form return ajax response
            content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')
示例#10
0
文件: cluster.py 项目: bsu/GWM2
def nodes(request, cluster_slug):
    """
    Display all nodes in a cluster
    """
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    user = request.user
    if not (user.is_superuser or user.has_perm('admin', cluster)):
        return render_403(request, _("You do not have sufficient privileges"))

    # query allocated CPUS for all nodes in this list.  Must be done here to
    # avoid querying Node.allocated_cpus for each node in the list.  Repackage
    # list so it is easier to retrieve the values in the template
    values = VirtualMachine.objects \
            .filter(cluster=cluster, status='running') \
            .exclude(virtual_cpus=-1) \
            .order_by() \
            .values('primary_node') \
            .annotate(cpus=Sum('virtual_cpus'))
    cpus = {}
    for d in values:
        cpus[d['primary_node']] = d['cpus']

    return render_to_response("ganeti/node/table.html",
        {'cluster': cluster,
         'nodes':cluster.nodes.all(),
         'cpus':cpus
        },
        context_instance=RequestContext(request),
    )
示例#11
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)):
        return render_403(request, _('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),
    )
示例#12
0
def replace_disks(request, cluster_slug, instance):
    """
    view used for initiating a Replace Disks job
    """
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)
    user = request.user
    if not (user.is_superuser or user.has_any_perms(cluster, ['admin','replace_disks'])):
        return render_403(request, _("You do not have sufficient privileges"))

    if request.method == 'POST':
        form = ReplaceDisksForm(vm, request.POST)
        if form.is_valid():
            try:
                job = form.save()
                job.refresh()
                content = json.dumps(job.info)

                # log information
                log_action('VM_REPLACE_DISKS', user, vm, job)
            except GanetiApiError, e:
                content = json.dumps({'__all__':[str(e)]})
        else:
            # error in form return ajax response
            content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')
示例#13
0
文件: jobs.py 项目: bsu/GWM2
def clear(request, cluster_slug, job_id, rest=False):
    """
    Clear a single failed job error message
    """
    
    user = request.user
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    job = get_object_or_404(Job, cluster__slug=cluster_slug, job_id=job_id)
    obj = job.obj

    # if not a superuser, check permissions on the object itself
    cluster_admin = user.is_superuser or user.has_perm('admin', cluster)

    if not cluster_admin:
        if isinstance(obj, (Cluster, Node)):
            if rest:
                return HttpResponseForbidden
            else:
                return render_403(request, _("You do not have sufficient privileges"))
        elif isinstance(obj, (VirtualMachine,)):
            # object is a virtual machine, check perms on VM and on Cluster
            if not (obj.owner_id == user.get_profile().pk  \
                or user.has_perm('admin', obj) \
                or user.has_perm('admin', obj.cluster)):
                    if rest:
                        return HttpResponseForbidden
                    else:
                        return render_403(request, _("You do not have sufficient privileges"))

    
    # clear the error.
    Job.objects.filter(pk=job.pk).update(cleared=True)

    # clear the job from the object, but only if it is the last job. It's
    # possible another job was started after this job, and the error message
    # just wasn't cleared.
    #
    # XXX object could be none, in which case we dont need to clear its last_job
    if obj is not None:
        ObjectModel = obj.__class__
        ObjectModel.objects.filter(pk=job.object_id, last_job=job)  \
            .update(last_job=None, ignore_cache=False)

    if rest:
        return 1
    else:
        return HttpResponse('1', mimetype='application/json')
示例#14
0
文件: importing.py 项目: bsu/GWM2
def missing_ganeti(request):
    """
    View for displaying VirtualMachines missing from the ganeti cluster
    """
    user = request.user
    if user.is_superuser:
        clusters = Cluster.objects.all()
    else:
        clusters = user.get_objects_any_perms(Cluster, ['admin'])
        if not clusters:
            return render_403(request, _('You do not have sufficient privileges'))

    vms = []
    for cluster in clusters:
        for vm in cluster.missing_in_ganeti:
            vms.append((vm, vm))
    
    if request.method == 'POST':
        # process updates if this was a form submission
        form = VirtualMachineForm(vms, request.POST)
        if form.is_valid():
            # update all selected VirtualMachines
            data = form.cleaned_data
            vm_ids = data['virtual_machines']
            q = VirtualMachine.objects.filter(hostname__in=vm_ids)

            missing = defaultdict(lambda:0)
            for i in q:
                missing[ i.cluster_id ] -= 1
            update_vm_counts(key='missing', data=missing)

            q.delete()
            
            # remove updated vms from the list
            vms = filter(lambda x: unicode(x[0]) not in vm_ids, vms)
    
    else:
        form = VirtualMachineForm(vms)

    vms = {}
    for cluster in clusters:
        for vm in cluster.missing_in_ganeti:
            vms[vm] = (cluster.hostname, vm)

    vmhostnames = vms.keys()
    vmhostnames.sort()

    vms_tuplelist = []
    for i in vmhostnames:
        vms_tuplelist.append((i, vms[i][0], vms[i][1]))

    vms = vms_tuplelist
        
    return render_to_response("ganeti/importing/missing.html", {
        'vms': vms,
        'form':form,
        },
        context_instance=RequestContext(request),
    )
示例#15
0
文件: cluster.py 项目: bsu/GWM2
def quota(request, cluster_slug, user_id):
    """
    Updates quota for a user
    """
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    user = request.user
    if not (user.is_superuser or user.has_perm('admin', cluster)):
        return render_403(request, _("You do not have sufficient privileges"))
    
    if request.method == 'POST':
        form = QuotaForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            cluster_user = data['user']
            if data['delete']:
                cluster.set_quota(cluster_user)
            else:
                quota = cluster.get_quota()
                same = data['virtual_cpus'] == quota['virtual_cpus'] \
                    and data['disk']==quota['disk'] \
                    and data['ram']==quota['ram']
                if same:
                    # same as default, set quota to default.
                    cluster.set_quota(cluster_user)
                else:
                    cluster.set_quota(cluster_user, data)
            
            # return updated html
            cluster_user = cluster_user.cast()
            url = reverse('cluster-permissions', args=[cluster.slug])
            if isinstance(cluster_user, (Profile,)):
                return render_to_response(
                    "ganeti/cluster/user_row.html",
                    {'object':cluster, 'user_detail':cluster_user.user, 'url':url},
                    context_instance=RequestContext(request))
            else:
                return render_to_response(
                    "ganeti/cluster/group_row.html",
                    {'object':cluster, 'group':cluster_user.group, 'url':url},
                    context_instance=RequestContext(request))
        
        # error in form return ajax response
        content = json.dumps(form.errors)
        return HttpResponse(content, mimetype='application/json')
    
    if user_id:
        cluster_user = get_object_or_404(ClusterUser, id=user_id)
        quota = cluster.get_quota(cluster_user)
        data = {'user':user_id}
        if quota:
            data.update(quota)
    else:
        return render_404(request, _('User was not found'))
    
    form = QuotaForm(data)
    return render_to_response("ganeti/cluster/quota.html",
                        {'form':form, 'cluster':cluster, 'user_id':user_id},
                        context_instance=RequestContext(request))
示例#16
0
文件: importing.py 项目: bsu/GWM2
def orphans(request):
    """
    displays list of orphaned VirtualMachines, i.e. VirtualMachines without
    an owner.
    """
    user = request.user
    if user.is_superuser:
        clusters = Cluster.objects.all()
    else:
        clusters = user.get_objects_any_perms(Cluster, ['admin'])
        if not clusters:
            return render_403(request, _('You do not have sufficient privileges'))
    
    vms_with_cluster = VirtualMachine.objects.filter(owner=None, cluster__in=clusters) \
                          .order_by('hostname').values_list('id','hostname','cluster')
    
    if request.method == 'POST':
        # strip cluster from vms
        vms = [(i[0], i[1]) for i in vms_with_cluster]
        
        # process updates if this was a form submission
        form = OrphanForm(vms, request.POST)
        if form.is_valid():
            # update all selected VirtualMachines
            data = form.cleaned_data
            owner = data['owner']
            vm_ids = data['virtual_machines']
            
            # update the owner and save the vm.  This isn't the most efficient
            # way of updating the VMs but we would otherwise need to group them
            # by cluster
            orphaned = defaultdict(lambda:0)
            for id in vm_ids:
                vm = VirtualMachine.objects.get(id=id)
                vm.owner = owner
                vm.save()
                orphaned[vm.cluster_id] -= 1
            update_vm_counts(key='orphaned', data=orphaned)
            
            # remove updated vms from the list
            vms_with_cluster = [i for i in vms_with_cluster
                if unicode(i[0]) not in vm_ids]

    else:
        # strip cluster from vms
        form = ImportForm([(i[0], i[1]) for i in vms_with_cluster])

    clusterdict = {}
    for i in clusters:
        clusterdict[i.id] = i.hostname
    vms = [ (i[0], clusterdict[i[2]], i[1]) for i in vms_with_cluster ]

    return render_to_response("ganeti/importing/orphans.html", {
        'vms': vms,
        'form':form,
        },
        context_instance=RequestContext(request),
    )
示例#17
0
def modify(request, cluster_slug, instance):
    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)):
        return render_403(request,
            'You do not have permissions to edit this virtual machine')
    
    hv_form = None
    hv = get_hypervisor(vm)
    if hv == 'kvm':
        hv_form = KvmModifyVirtualMachineForm
    elif hv == 'xen-pvm':
        hv_form = PvmModifyVirtualMachineForm
    elif hv == 'xen-hvm':
        hv_form = HvmModifyVirtualMachineForm

    if request.method == 'POST':
        
        form = hv_form(vm, request.POST)
        
        form.owner = vm.owner
        form.vm = vm
        form.cluster = cluster
        if form.is_valid():
            data = form.cleaned_data
            request.session['edit_form'] = data
            request.session['edit_vm'] = vm.id
            return HttpResponseRedirect(
            reverse('instance-modify-confirm', args=[cluster.slug, vm.hostname]))

    elif request.method == 'GET':
        if 'edit_form' in request.session and vm.id == request.session['edit_vm']:
            form = hv_form(vm, request.session['edit_form'])
        else:
            form = hv_form(vm)
 
    # Select template depending on hypervisor
    # Default to edit_base
    if hv == 'kvm':
        template = 'ganeti/virtual_machine/edit_kvm.html'
    elif hv == 'xen-hvm':
        template = 'ganeti/virtual_machine/edit_hvm.html'
    elif hv == 'xen-pvm':
        template = 'ganeti/virtual_machine/edit_pvm.html'
    else:
        template = 'ganeti/virtual_machine/edit_base.html'

    return render_to_response(template, {
        'cluster': cluster,
        'instance': vm,
        'form': form,
        },
        context_instance=RequestContext(request),
    )
示例#18
0
def importing(request):
    """
    View that loads main importing view
    """
    user = request.user
    if not user.is_superuser or user.get_objects_any_perms(Cluster, ['admin']):
        return render_403(request, _('You do not have sufficient privileges'))

    return render_to_response('ganeti/importing/nodes/main.html',
              context_instance=RequestContext(request))
示例#19
0
文件: cluster.py 项目: bsu/GWM2
def users(request, cluster_slug):
    """
    Display all of the Users of a Cluster
    """
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    
    user = request.user
    if not (user.is_superuser or user.has_perm('admin', cluster)):
        return render_403(request, _("You do not have sufficient privileges"))
    
    url = reverse('cluster-permissions', args=[cluster.slug])
    return view_users(request, cluster, url, template='ganeti/cluster/users.html')
示例#20
0
def rename(request, cluster_slug, instance, rest=False, extracted_params=None):
    """
    Rename an existing instance
    """
    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)):
        return render_403(request,
            _('You do not have permissions to edit this virtual machine'))

    if request.method == 'POST':
        form = RenameForm(vm, request.POST)
        params_ok = False
        if ((rest) & (extracted_params != None)):
            if ((extracted_params.has_key('hostname')) & (extracted_params.has_key('ip_check')) & (extracted_params.has_key('name_check'))):
                hostname = extracted_params.get('hostname')
                ip_check = extracted_params.get('ip_check')
                name_check = extracted_params.get('name_check')
                params_ok = True
            else:
                return HttpResponseBadRequest

        if (form.is_valid()):
            data = form.cleaned_data
            hostname = data['hostname']
            ip_check = data['ip_check']
            name_check = data['name_check']

        if (form.is_valid() | params_ok):
            try:
                job_id = vm.rapi.RenameInstance(vm.hostname, hostname,
                                                ip_check, name_check)
                job = Job.objects.create(job_id=job_id, obj=vm, cluster=cluster)
                VirtualMachine.objects.filter(pk=vm.pk) \
                    .update(hostname=hostname, last_job=job, ignore_cache=True)

                # log information about creating the machine
                log_action('VM_RENAME', user, vm, job)

                if not rest:
                    return HttpResponseRedirect(
                    reverse('instance-detail', args=[cluster.slug, hostname]))
                else:
                    return HttpAccepted

            except GanetiApiError, e:
                msg = 'Error renaming virtual machine: %s' % e
                form._errors["cluster"] = form.error_class([msg])
                if rest:
                    return HttpResponse(400, content=msg)
示例#21
0
文件: general.py 项目: bsu/GWM2
def clear_ganeti_error(request, pk):
    """
    Clear a single error message
    """
    user = request.user
    error = get_object_or_404(GanetiError, pk=pk)
    obj = error.obj
    
    # if not a superuser, check permissions on the object itself
    if not user.is_superuser:
        if isinstance(obj, (Cluster,)) and not user.has_perm('admin', obj):
            return render_403(request, _("You do not have sufficient privileges"))
        elif isinstance(obj, (VirtualMachine,)):
            # object is a virtual machine, check perms on VM and on Cluster
            if not (obj.owner_id == user.get_profile().pk or \
                user.has_perm('admin', obj.cluster)):
                    return render_403(request, _("You do not have sufficient privileges"))
    
    # clear the error
    GanetiError.objects.filter(pk=error.pk).update(cleared=True)
    
    return HttpResponse('1', mimetype='application/json')
示例#22
0
文件: cluster.py 项目: bsu/GWM2
def permissions(request, cluster_slug, user_id=None, group_id=None):
    """
    Update a users permissions. This wraps object_permissions.view_permissions()
    with our custom permissions checks.
    """
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    user = request.user
    if not (user.is_superuser or user.has_perm('admin', cluster)):
        return render_403(request, "You do not have sufficient privileges")

    url = reverse('cluster-permissions', args=[cluster.slug])
    return view_permissions(request, cluster, url, user_id, group_id,
                            user_template='ganeti/cluster/user_row.html',
                            group_template='ganeti/cluster/group_row.html')
示例#23
0
def delete(request, cluster_slug, instance, rest=False):
    """
    Delete a VM.
    """

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

    # Check permissions.
    if not (
        user.is_superuser or
        user.has_any_perms(instance, ["remove", "admin"]) or
        user.has_perm("admin", cluster)
        ):
        if not rest:
            return render_403(request, _('You do not have sufficient privileges'))
        else:
            return HttpResponseForbidden()

    if (request.method == 'GET') & (not rest):
        return render_to_response("ganeti/virtual_machine/delete.html",
            {'vm': instance, 'cluster':cluster},
            context_instance=RequestContext(request),
        )

    elif (request.method == 'POST') | rest:
        # verify that this instance actually exists in ganeti.  If it doesn't
        # exist it can just be deleted.
        try:
            instance._refresh()
        except GanetiApiError, e:
            if e.code == 404:
                instance.delete()
                if not rest:
                    return HttpResponseRedirect(reverse('virtualmachine-list'))
                else:
                    return HttpAccepted()

        # start deletion job and mark the VirtualMachine as pending_delete and
        # disable the cache for this VM.
        job_id = instance.rapi.DeleteInstance(instance.hostname)
        job = Job.objects.create(job_id=job_id, obj=instance, cluster_id=instance.cluster_id)
        VirtualMachine.objects.filter(id=instance.id) \
            .update(last_job=job, ignore_cache=True, pending_delete=True)

        if not rest:
            return HttpResponseRedirect(
                reverse('instance-detail', args=[cluster_slug, instance.hostname]))
        else:
            return HttpAccepted()
示例#24
0
def permissions(request, cluster_slug, instance, user_id=None, group_id=None):
    """
    Update a users permissions.
    """
    vm = get_object_or_404(VirtualMachine, hostname=instance,
                           cluster__slug=cluster_slug)

    user = request.user
    if not (user.is_superuser or user.has_perm('admin', vm) or
        user.has_perm('admin', vm.cluster)):
        return render_403(request, _("You do not have sufficient privileges"))

    url = reverse('vm-permissions', args=[cluster_slug, vm.hostname])
    return view_permissions(request, vm, url, user_id, group_id)
示例#25
0
def missing_ganeti(request):
    """
    View for displaying VirtualMachines missing from the ganeti cluster
    """
    user = request.user
    if user.is_superuser:
        clusters = Cluster.objects.all()
    else:
        clusters = user.get_objects_any_perms(Cluster, ['admin'])
        if not clusters:
            return render_403(request, _('You do not have sufficient privileges'))

    nodes = []
    for cluster in clusters:
        for node in cluster.nodes_missing_in_ganeti:
            nodes.append((node, node))

    if request.method == 'POST':
        # process updates if this was a form submission
        form = NodeForm(nodes, request.POST)
        if form.is_valid():
            # update all selected Nodes
            data = form.cleaned_data
            node_ids = data['nodes']
            Node.objects.filter(hostname__in=node_ids).delete()

    else:
        form = NodeForm(nodes)

    nodes = {}
    for cluster in clusters:
        for node in cluster.nodes_missing_in_ganeti:
            nodes[node] = (cluster.hostname, node)

    node_hostnames = nodes.keys()
    node_hostnames.sort()

    node_tuple_list = []
    for i in node_hostnames:
        node_tuple_list.append((i, nodes[i][0], nodes[i][1]))

    nodes = node_tuple_list

    return render_to_response("ganeti/importing/nodes/missing.html"
                              , {
        'nodes': nodes,
        'form':form,
        },
        context_instance=RequestContext(request),
    )
示例#26
0
文件: node.py 项目: bsu/GWM2
def object_log(request, cluster_slug, host, rest=False):
    """
    Display object log for this node
    """
    node, cluster = get_node_and_cluster_or_404(cluster_slug, host)

    user = request.user
    if not (user.is_superuser or user.has_any_perms(cluster, ['admin','migrate'])):
        if not rest:
            return render_403(request, _("You do not have sufficient privileges"))
        else:
            return {'error':'You do not have sufficient privileges'}

    return list_for_object(request, node, rest)
示例#27
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)
        ):
        return render_403(request, _('You do not have sufficient privileges'))

    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]))

    return HttpResponseNotAllowed(["GET","POST"])
示例#28
0
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'])):
        return render_403(request, _('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')
示例#29
0
def users(request, cluster_slug, instance, rest=False):
    """
    Display all of the Users of a VirtualMachine
    """
    vm, cluster = get_vm_and_cluster_or_404(cluster_slug, instance)

    user = request.user
    if not (user.is_superuser or user.has_perm('admin', vm) or
        user.has_perm('admin', cluster)):
        if not rest:
            return render_403(request, _("You do not have sufficient privileges"))
        else:
            return {'msg':'You do not have sufficient privileges', 'code':403}

    url = reverse('vm-permissions', args=[cluster.slug, vm.hostname])
    return view_users(request, vm, url, rest = True)
示例#30
0
def object_log(request, cluster_slug, instance, rest=False):
    """
    Display all of the Users of a VirtualMachine
    """
    cluster = get_object_or_404(Cluster, slug=cluster_slug)
    vm = get_object_or_404(VirtualMachine, hostname=instance)

    user = request.user
    if not (user.is_superuser or user.has_perm('admin', vm) or
        user.has_perm('admin', cluster)):
        return render_403(request, _("You do not have sufficient privileges"))

    if not rest:
        return list_for_object(request, vm)
    else:
        return list_for_object(request, vm, True)