views.py 6.7 KB
Newer Older
1 2
from os import getenv
import json
Őry Máté committed
3
import logging
4 5 6
import re

from django.contrib.auth.models import User, Group
7
from django.core import signing
8 9
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
10
from django.shortcuts import redirect
11 12
from django.views.generic import TemplateView, DetailView, View
from django.views.generic.detail import SingleObjectMixin
13
from django.http import HttpResponse
14

15
from django_tables2 import SingleTableView
Kálmán Viktor committed
16

17
from .tables import VmListTable
18
from vm.models import Instance, InstanceTemplate, InterfaceTemplate
19
from firewall.models import Vlan
20
from storage.models import Disk
21

Őry Máté committed
22 23
logger = logging.getLogger(__name__)

24 25

class IndexView(TemplateView):
Kálmán Viktor committed
26
    template_name = "dashboard/index.html"
27

28
    def get_context_data(self, **kwargs):
29 30 31 32 33
        if self.request.user.is_authenticated():
            user = self.request.user
        else:
            user = None

34
        instances = Instance.objects.filter(owner=user)
35 36
        context = super(IndexView, self).get_context_data(**kwargs)
        context.update({
37
            'instances': instances[:5],
38
            'more_instances': instances.count() - len(instances[:5])
39 40 41
        })

        context.update({
42 43
            'running_vms': instances.filter(state='RUNNING'),
            'running_vm_num': instances.filter(state='RUNNING').count(),
44 45
            'stopped_vm_num': instances.exclude(
                state__in=['RUNNING', 'NOSTATE']).count()
46 47 48
        })
        return context

49

50 51 52 53 54 55 56 57 58 59
def get_acl_data(obj):
    levels = obj.ACL_LEVELS
    users = obj.get_users_with_level()
    users = [{'user': u, 'level': l} for u, l in users]
    groups = obj.get_groups_with_level()
    groups = [{'group': g, 'level': l} for g, l in groups]
    return {'users': users, 'groups': groups, 'levels': levels,
            'url': reverse('dashboard.views.vm-acl', args=[obj.pk])}


60
class VmDetailView(DetailView):
Kálmán Viktor committed
61
    template_name = "dashboard/vm-detail.html"
62
    model = Instance
63 64

    def get_context_data(self, **kwargs):
65
        context = super(VmDetailView, self).get_context_data(**kwargs)
66 67 68
        instance = context['instance']
        if instance.node:
            port = instance.vnc_port
69
            host = str(instance.node.host.ipv4)
70
            value = signing.dumps({'host': host,
71 72
                                   'port': port},
                                  key=getenv("PROXY_SECRET", 'asdasd')),
73 74 75
            context.update({
                'vnc_url': '%s' % value
            })
76
        context['acl'] = get_acl_data(instance)
77
        return context
Kálmán Viktor committed
78

79 80

class AclUpdateView(View, SingleObjectMixin):
81

82
    def post(self, request, *args, **kwargs):
83
        instance = self.get_object()
84
        if not instance.has_level(request.user, "owner"):
Őry Máté committed
85 86
            logger.warning('Tried to set permissions of %s by non-owner %s.',
                           unicode(instance), unicode(request.user))
87
            raise PermissionDenied()
88 89 90 91 92
        for key, value in request.POST.items():
            m = re.match('perm-([ug])-(\d+)', key)
            if m:
                type, id = m.groups()
                entity = {'u': User, 'g': Group}[type].objects.get(id=id)
93
                instance.set_level(entity, value)
Őry Máté committed
94 95 96
                logger.info("Set %s's acl level for %s to %s by %s.",
                            unicode(entity), unicode(instance),
                            value, unicode(request.user))
97 98 99 100 101 102 103 104

        name = request.POST['perm-new-name']
        value = request.POST['perm-new']
        if name:
            try:
                entity = User.objects.get(username=name)
            except User.DoesNotExist:
                entity = Group.objects.get(name=name)
105
            instance.set_level(entity, value)
106
        return redirect(instance)
Őry Máté committed
107 108 109
        logger.info("Set %s's new acl level for %s to %s by %s.",
                    unicode(entity), unicode(instance),
                    value, unicode(request.user))
110

Kálmán Viktor committed
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
class TemplateDetail(DetailView):
    model = InstanceTemplate

    def get(self, request, *args, **kwargs):
        if request.is_ajax():
            template = InstanceTemplate.objects.get(pk=kwargs['pk'])
            template = {
                'num_cores': template.num_cores,
                'ram_size': template.ram_size,
                'priority': template.priority,
                'arch': template.arch,
                'description': template.description,
                'system': template.system,
                'name': template.name,
                'disks': [{'pk': d.pk, 'name': d.name}
                          for d in template.disks.all()],
                'network': [
                    {'vlan_pk': i.vlan.pk, 'vlan': i.vlan.name,
                     'managed': i.managed}
                    for i in InterfaceTemplate.objects.filter(
                        template=self.get_object()).all()
                ]
            }
            return HttpResponse(json.dumps(template),
                                content_type="application/json")
        else:
            # return super(TemplateDetail, self).get(request, *args, **kwargs)
            return HttpResponse('soon')


142
class VmList(SingleTableView):
Kálmán Viktor committed
143
    template_name = "dashboard/vm-list.html"
144 145
    model = Instance
    table_class = VmListTable
146
    table_pagination = False
147 148 149 150 151 152


class VmCreate(TemplateView):

    def get_template_names(self):
        if self.request.is_ajax():
153
            return ['dashboard/modal-wrapper.html']
154
        else:
155
            return ['dashboard/nojs-wrapper.html']
156 157 158

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
159 160 161 162
        context.update({
            'template': 'dashboard/vm-create.html',
            'box_title': 'Create a VM'
        })
163
        return self.render_to_response(context)
164 165 166

    def get_context_data(self, **kwargs):
        context = super(VmCreate, self).get_context_data(**kwargs)
167
        # TODO acl
168
        context.update({
169
            'templates': InstanceTemplate.objects.all(),
170
            'vlans': Vlan.objects.all(),
171
            'disks': Disk.objects.exclude(type="qcow2-snap")
172 173 174
        })

        return context
175 176

    def post(self, request, *args, **kwargs):
177 178 179 180 181
        if self.request.user.is_authenticated():
            user = self.request.user
        else:
            user = None

182 183 184 185 186
        resp = request.POST.copy()
        resp['managed-vlans'] = request.POST.getlist('managed-vlans')
        resp['unmanaged-vlans'] = request.POST.getlist('unmanaged-vlans')
        resp['disks'] = request.POST.getlist('disks')

187 188 189 190 191 192
        template = InstanceTemplate.objects.get(
            pk=request.POST.get('template-pk'))
        inst = Instance.create_from_template(template=template, owner=user)
        inst.deploy_async()

        # TODO handle response
193
        return HttpResponse(json.dumps(resp), content_type="application/json")