vm.py 48.7 KB
Newer Older
Őry Máté committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals, absolute_import

import json
import logging
from collections import OrderedDict
from os import getenv

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
27
from django.contrib.auth.decorators import login_required
Őry Máté committed
28 29 30
from django.core import signing
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.core.urlresolvers import reverse, reverse_lazy
31 32 33
from django.http import (
    HttpResponse, Http404, HttpResponseRedirect, JsonResponse
)
34
from django.shortcuts import redirect, get_object_or_404
Őry Máté committed
35 36 37 38 39 40
from django.template.loader import render_to_string
from django.utils.translation import (
    ugettext as _, ugettext_noop, ungettext_lazy,
)
from django.views.decorators.http import require_GET
from django.views.generic import (
41
    UpdateView, ListView, TemplateView
Őry Máté committed
42 43 44 45 46 47
)

from braces.views import SuperuserRequiredMixin, LoginRequiredMixin

from common.models import (
    create_readable, HumanReadableException, fetch_human_exception,
48
    split_activity_code,
Őry Máté committed
49 50
)
from firewall.models import Vlan, Host, Rule
51
from manager.scheduler import SchedulerError
Őry Máté committed
52 53
from storage.models import Disk
from vm.models import (
54
    Instance, InstanceActivity, Node, Lease,
Őry Máté committed
55 56 57 58
    InstanceTemplate, InterfaceTemplate, Interface,
)
from .util import (
    CheckedDetailView, AjaxOperationMixin, OperationView, AclUpdateView,
59 60
    FormOperationMixin, FilterMixin, GraphMixin,
    TransferOwnershipConfirmView, TransferOwnershipView,
Őry Máté committed
61 62 63
)
from ..forms import (
    AclUserOrGroupAddForm, VmResourcesForm, TraitsForm, RawDataForm,
64 65
    VmAddInterfaceForm, VmCreateDiskForm, VmDownloadDiskForm,
    VmImportDiskForm, VmSaveForm,
Őry Máté committed
66
    VmRenewForm, VmStateChangeForm, VmListSearchForm, VmCustomizeForm,
67
    VmDiskExportForm, VmDiskResizeForm, RedeployForm, VmDiskRemoveForm,
68
    VmMigrateForm, VmDeployForm,
69
    VmPortRemoveForm, VmPortAddForm,
70
    VmRemoveInterfaceForm,
71
    VmRenameForm,
Őry Máté committed
72
)
73
from request.models import TemplateAccessType, LeaseType
74
from request.forms import LeaseRequestForm, TemplateRequestForm
75
from ..models import Favourite
76
from manager.scheduler import has_traits
Őry Máté committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

logger = logging.getLogger(__name__)


class VmDetailVncTokenView(CheckedDetailView):
    template_name = "dashboard/vm-detail.html"
    model = Instance

    def get(self, request, **kwargs):
        self.object = self.get_object()
        if not self.object.has_level(request.user, 'operator'):
            raise PermissionDenied()
        if not request.user.has_perm('vm.access_console'):
            raise PermissionDenied()
        if self.object.node:
92 93 94 95
            with self.object.activity(
                    code_suffix='console-accessed', user=request.user,
                    readable_name=ugettext_noop("console access"),
                    concurrency_check=False):
Őry Máté committed
96 97 98 99 100 101 102 103 104
                port = self.object.vnc_port
                host = str(self.object.node.host.ipv4)
                value = signing.dumps({'host': host, 'port': port},
                                      key=getenv("PROXY_SECRET", 'asdasd')),
                return HttpResponse('vnc/?d=%s' % value)
        else:
            raise Http404()


105
class VmDetailView(GraphMixin, CheckedDetailView):
Őry Máté committed
106 107 108
    template_name = "dashboard/vm-detail.html"
    model = Instance

109 110 111 112 113 114 115 116 117 118 119 120 121
    def get(self, *args, **kwargs):
        if self.request.is_ajax():
            return JsonResponse(self.get_json_data())
        else:
            return super(VmDetailView, self).get(*args, **kwargs)

    def get_json_data(self):
        instance = self.get_object()
        return {"status": instance.status,
                "host": instance.get_connect_host(),
                "port": instance.get_connect_port(),
                "password": instance.pw}

Őry Máté committed
122 123 124 125
    def get_context_data(self, **kwargs):
        context = super(VmDetailView, self).get_context_data(**kwargs)
        instance = context['instance']
        user = self.request.user
126 127
        is_operator = instance.has_level(user, "operator")
        is_owner = instance.has_level(user, "owner")
Őry Máté committed
128
        ops = get_operations(instance, user)
129 130
        hide_tutorial = self.request.COOKIES.get(
            "hide_tutorial_for_%s" % instance.pk) == "True"
Őry Máté committed
131 132 133 134 135 136
        context.update({
            'graphite_enabled': settings.GRAPHITE_URL is not None,
            'vnc_url': reverse_lazy("dashboard.views.detail-vnc",
                                    kwargs={'pk': self.object.pk}),
            'ops': ops,
            'op': {i.op: i for i in ops},
137 138
            'connect_commands': user.profile.get_connect_commands(instance),
            'hide_tutorial': hide_tutorial,
139
            'fav': instance.favourite_set.filter(user=user).exists(),
Őry Máté committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        })

        # activity data
        activities = instance.get_merged_activities(user)
        show_show_all = len(activities) > 10
        activities = activities[:10]
        context['activities'] = _format_activities(activities)
        context['show_show_all'] = show_show_all
        latest = instance.get_latest_activity_in_progress()
        context['is_new_state'] = (latest and
                                   latest.resultant_state is not None and
                                   instance.status != latest.resultant_state)

        context['vlans'] = Vlan.get_objects_with_level(
            'user', self.request.user
        ).exclude(  # exclude already added interfaces
            pk__in=Interface.objects.filter(
                instance=self.get_object()).values_list("vlan", flat=True)
        ).all()
        context['acl'] = AclUpdateView.get_acl_data(
            instance, self.request.user, 'dashboard.views.vm-acl')
        context['aclform'] = AclUserOrGroupAddForm()
        context['os_type_icon'] = instance.os_type.replace("unknown",
                                                           "question")
        # ipv6 infos
        context['ipv6_host'] = instance.get_connect_host(use_ipv6=True)
        context['ipv6_port'] = instance.get_connect_port(use_ipv6=True)

        # resources forms
        can_edit = (
170 171
                instance.has_level(user, "owner") and
                self.request.user.has_perm("vm.change_resources"))
Őry Máté committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
        context['resources_form'] = VmResourcesForm(
            can_edit=can_edit, instance=instance)

        if self.request.user.is_superuser:
            context['traits_form'] = TraitsForm(instance=instance)
            context['raw_data_form'] = RawDataForm(instance=instance)

        # resources change perm
        context['can_change_resources'] = self.request.user.has_perm(
            "vm.change_resources")

        # client info
        context['client_download'] = self.request.COOKIES.get(
            'downloaded_client')
        # can link template
187 188 189 190 191
        context['can_link_template'] = instance.template and is_operator

        # is operator/owner
        context['is_operator'] = is_operator
        context['is_owner'] = is_owner
Őry Máté committed
192

193
        # operation also allows RUNNING (if with_shutdown is present)
194 195
        context['save_resources_enabled'] = instance.status in (
            "STOPPED",
196
            "PENDING",
197
        )
198

Őry Máté committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        return context

    def post(self, request, *args, **kwargs):
        options = {
            'new_description': self.__set_description,
            'new_tag': self.__add_tag,
            'to_remove': self.__remove_tag,
            'abort_operation': self.__abort_operation,
        }
        for k, v in options.iteritems():
            if request.POST.get(k) is not None:
                return v(request)
        raise Http404()

    def __set_description(self, request):
        self.object = self.get_object()
215
        if not self.object.has_level(request.user, "operator"):
Őry Máté committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
            raise PermissionDenied()

        new_description = request.POST.get("new_description")
        Instance.objects.filter(pk=self.object.pk).update(
            **{'description': new_description})

        success_message = _("VM description successfully updated.")
        if request.is_ajax():
            response = {
                'message': success_message,
                'new_description': new_description,
            }
            return HttpResponse(
                json.dumps(response),
                content_type="application/json"
            )
        else:
            messages.success(request, success_message)
            return redirect(self.object.get_absolute_url())

    def __add_tag(self, request):
        new_tag = request.POST.get('new_tag')
        self.object = self.get_object()
239
        if not self.object.has_level(request.user, "operator"):
Őry Máté committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
            raise PermissionDenied()

        if len(new_tag) < 1:
            message = u"Please input something."
        elif len(new_tag) > 20:
            message = u"Tag name is too long."
        else:
            self.object.tags.add(new_tag)

        try:
            messages.error(request, message)
        except:
            pass

        return redirect(reverse_lazy("dashboard.views.detail",
                                     kwargs={'pk': self.object.pk}))

    def __remove_tag(self, request):
        try:
            to_remove = request.POST.get('to_remove')
            self.object = self.get_object()
261
            if not self.object.has_level(request.user, "operator"):
Őry Máté committed
262 263 264 265 266 267 268 269
                raise PermissionDenied()

            self.object.tags.remove(to_remove)
            message = u"Success"
        except:  # note this won't really happen
            message = u"Not success"

        if request.is_ajax():
270
            return JsonResponse({'message': message})
Őry Máté committed
271 272
        else:
            return redirect(reverse_lazy("dashboard.views.detail",
273
                                         kwargs={'pk': self.object.pk}))
Őry Máté committed
274 275 276 277 278 279 280 281 282

    def __abort_operation(self, request):
        self.object = self.get_object()

        activity = get_object_or_404(InstanceActivity,
                                     pk=request.POST.get("activity"))
        if not activity.is_abortable_for(request.user):
            raise PermissionDenied()
        activity.abort()
Őry Máté committed
283 284
        return HttpResponseRedirect("%s#activity" %
                                    self.object.get_absolute_url())
Őry Máté committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325


class VmTraitsUpdate(SuperuserRequiredMixin, UpdateView):
    form_class = TraitsForm
    model = Instance

    def get_success_url(self):
        return self.get_object().get_absolute_url() + "#resources"


class VmRawDataUpdate(SuperuserRequiredMixin, UpdateView):
    form_class = RawDataForm
    model = Instance
    template_name = 'dashboard/vm-detail/raw_data.html'

    def get_success_url(self):
        return self.get_object().get_absolute_url() + "#resources"


class VmOperationView(AjaxOperationMixin, OperationView):
    model = Instance
    context_object_name = 'instance'  # much simpler to mock object


def get_operations(instance, user):
    ops = []
    for k, v in vm_ops.iteritems():
        try:
            op = v.get_op_by_object(instance)
            op.check_auth(user)
            op.check_precond()
        except PermissionDenied as e:
            logger.debug('Not showing operation %s for %s: %s',
                         k, instance, unicode(e))
        except Exception:
            ops.append(v.bind_to_object(instance, disabled=True))
        else:
            ops.append(v.bind_to_object(instance))
    return ops


326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
class VmRemoveInterfaceView(FormOperationMixin, VmOperationView):
    op = 'remove_interface'
    form_class = VmRemoveInterfaceForm
    show_in_toolbar = False
    wait_for_result = 0.5
    icon = 'times'
    effect = "danger"
    with_reload = True

    def get_form_kwargs(self):
        instance = self.get_op().instance
        choices = instance.interface_set.all()
        interface_pk = self.request.GET.get('interface')
        if interface_pk:
            try:
                default = choices.get(pk=interface_pk)
            except (ValueError, Interface.DoesNotExist):
                raise Http404()
        else:
            default = None

        val = super(VmRemoveInterfaceView, self).get_form_kwargs()
        val.update({'choices': choices, 'default': default})
        return val


Őry Máté committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
class VmAddInterfaceView(FormOperationMixin, VmOperationView):
    op = 'add_interface'
    form_class = VmAddInterfaceForm
    show_in_toolbar = False
    icon = 'globe'
    effect = 'success'
    with_reload = True

    def get_form_kwargs(self):
        inst = self.get_op().instance
        choices = Vlan.get_objects_with_level(
            "user", self.request.user).exclude(
            vm_interface__instance__in=[inst])
        val = super(VmAddInterfaceView, self).get_form_kwargs()
        val.update({'choices': choices})
        return val


370
class VmDiskModifyView(FormOperationMixin, VmOperationView):
371
    show_in_toolbar = False
372
    with_reload = True
373 374 375 376 377 378 379 380 381 382
    icon = 'arrows-alt'
    effect = "success"

    def get_form_kwargs(self):
        choices = self.get_op().instance.disks
        disk_pk = self.request.GET.get('disk')
        if disk_pk:
            try:
                default = choices.get(pk=disk_pk)
            except (ValueError, Disk.DoesNotExist):
383
                raise Http404()
384
        else:
385
            default = None
386

387
        val = super(VmDiskModifyView, self).get_form_kwargs()
388 389 390 391
        val.update({'choices': choices, 'default': default})
        return val


Őry Máté committed
392 393 394 395 396 397 398
class VmCreateDiskView(FormOperationMixin, VmOperationView):
    op = 'create_disk'
    form_class = VmCreateDiskForm
    show_in_toolbar = False
    icon = 'hdd-o'
    effect = "success"
    is_disk_operation = True
399
    with_reload = True
Őry Máté committed
400

401 402 403 404 405 406
    def get_form_kwargs(self):
        op = self.get_op()
        val = super(VmCreateDiskView, self).get_form_kwargs()
        num = op.instance.disks.count() + 1
        val['default'] = "%s %d" % (op.instance.name, num)
        return val
Őry Máté committed
407 408


409 410 411 412 413 414 415 416 417
class VmImportDiskView(FormOperationMixin, VmOperationView):
    op = 'import_disk'
    form_class = VmImportDiskForm
    show_in_toolbar = False
    icon = 'upload'
    effect = "success"
    is_disk_operation = True
    with_reload = True

418 419 420 421
    def get_form_kwargs(self):
        val = super(VmImportDiskView, self).get_form_kwargs()
        val.update({'user': self.request.user})
        return val
422

Őry Máté committed
423

424
class VmDownloadDiskView(FormOperationMixin, VmOperationView):
Őry Máté committed
425 426 427 428 429 430
    op = 'download_disk'
    form_class = VmDownloadDiskForm
    show_in_toolbar = False
    icon = 'download'
    effect = "success"
    is_disk_operation = True
431
    with_reload = True
Őry Máté committed
432 433


434
class VmMigrateView(FormOperationMixin, VmOperationView):
Őry Máté committed
435 436 437 438
    op = 'migrate'
    icon = 'truck'
    effect = 'info'
    template_name = 'dashboard/_vm-migrate.html'
439
    form_class = VmMigrateForm
Őry Máté committed
440

441 442 443 444
    def get_form_kwargs(self):
        online = (n.pk for n in Node.objects.filter(enabled=True) if n.online)
        choices = Node.objects.filter(pk__in=online)
        default = None
445 446 447
        inst = self.get_object()
        try:
            if isinstance(inst, Instance):
448
                default = inst.select_node()
449
        except SchedulerError:
450
            logger.exception("scheduler error:")
451

452 453 454
        val = super(VmMigrateView, self).get_form_kwargs()
        val.update({'choices': choices, 'default': default})
        return val
Őry Máté committed
455

456 457 458 459 460 461 462 463
    def get_context_data(self, *args, **kwargs):
        ctx = super(VmMigrateView, self).get_context_data(*args, **kwargs)

        inst = self.get_object()
        if isinstance(inst, Instance):
            nodes_w_traits = [
                n.pk for n in Node.objects.filter(enabled=True)
                if n.online and
464
                   has_traits(inst.req_traits.all(), n)
465 466 467 468 469
            ]
            ctx['nodes_w_traits'] = nodes_w_traits

        return ctx

Őry Máté committed
470

471
class VmPortRemoveView(FormOperationMixin, VmOperationView):
472
    template_name = 'dashboard/_vm-remove-port.html'
473 474 475
    op = 'remove_port'
    show_in_toolbar = False
    with_reload = True
Bach Dániel committed
476
    wait_for_result = 0.5
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    icon = 'times'
    effect = "danger"
    form_class = VmPortRemoveForm

    def get_form_kwargs(self):
        instance = self.get_op().instance
        choices = Rule.portforwards().filter(
            host__interface__instance=instance)
        rule_pk = self.request.GET.get('rule')
        if rule_pk:
            try:
                default = choices.get(pk=rule_pk)
            except (ValueError, Rule.DoesNotExist):
                raise Http404()
        else:
            default = None

        val = super(VmPortRemoveView, self).get_form_kwargs()
        val.update({'choices': choices, 'default': default})
        return val


499 500 501 502
class VmPortAddView(FormOperationMixin, VmOperationView):
    op = 'add_port'
    show_in_toolbar = False
    with_reload = True
Bach Dániel committed
503 504
    wait_for_result = 0.5
    icon = 'plus'
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
    effect = "success"
    form_class = VmPortAddForm

    def get_form_kwargs(self):
        instance = self.get_op().instance
        choices = Host.objects.filter(interface__instance=instance)
        host_pk = self.request.GET.get('host')
        if host_pk:
            try:
                default = choices.get(pk=host_pk)
            except (ValueError, Host.DoesNotExist):
                raise Http404()
        else:
            default = None

        val = super(VmPortAddView, self).get_form_kwargs()
        val.update({'choices': choices, 'default': default})
        return val


Őry Máté committed
525 526 527 528 529 530
class VmSaveView(FormOperationMixin, VmOperationView):
    op = 'save_as_template'
    icon = 'save'
    effect = 'info'
    form_class = VmSaveForm

531 532 533 534
    def get_form_kwargs(self):
        op = self.get_op()
        val = super(VmSaveView, self).get_form_kwargs()
        val['default'] = op._rename(op.instance.name)
535 536 537 538
        obj = self.get_object()
        if obj.template and obj.template.has_level(
                self.request.user, "owner"):
            val['clone'] = True
539 540
        return val

Őry Máté committed
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

class VmResourcesChangeView(VmOperationView):
    op = 'resources_change'
    icon = "save"
    show_in_toolbar = False
    wait_for_result = 0.5

    def post(self, request, extra=None, *args, **kwargs):
        if extra is None:
            extra = {}

        instance = get_object_or_404(Instance, pk=kwargs['pk'])

        form = VmResourcesForm(request.POST, instance=instance)
        if not form.is_valid():
            for f in form.errors:
                messages.error(request, "<strong>%s</strong>: %s" % (
                    f, form.errors[f].as_text()
                ))
            if request.is_ajax():  # this is not too nice
                store = messages.get_messages(request)
                store.used = True
563 564
                return JsonResponse({'success': False,
                                     'messages': [unicode(m) for m in store]})
Őry Máté committed
565
            else:
566 567
                return HttpResponseRedirect(instance.get_absolute_url() +
                                            "#resources")
Őry Máté committed
568 569 570 571 572 573 574 575 576 577 578 579 580
        else:
            extra = form.cleaned_data
            extra['max_ram_size'] = extra['ram_size']
            return super(VmResourcesChangeView, self).post(request, extra,
                                                           *args, **kwargs)


class TokenOperationView(OperationView):
    """Abstract operation view with token support.

    User can do the action with a valid token instead of logging in.
    """
    token_max_age = 3 * 24 * 3600
581
    redirect_exception_classes = (PermissionDenied, SuspiciousOperation,)
Őry Máté committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654

    @classmethod
    def get_salt(cls):
        return unicode(cls)

    @classmethod
    def get_token(cls, instance, user):
        t = tuple([getattr(i, 'pk', i) for i in [instance, user]])
        return signing.dumps(t, salt=cls.get_salt(), compress=True)

    @classmethod
    def get_token_url(cls, instance, user):
        key = cls.get_token(instance, user)
        return cls.get_instance_url(instance.pk, key)

    def check_auth(self):
        if 'k' in self.request.GET:
            try:  # check if token is needed at all
                return super(TokenOperationView, self).check_auth()
            except Exception:
                op = self.get_op()
                pk = op.instance.pk
                key = self.request.GET.get('k')

                logger.debug("checking token supplied to %s",
                             self.request.get_full_path())
                try:
                    user = self.validate_key(pk, key)
                except signing.SignatureExpired:
                    messages.error(self.request, _('The token has expired.'))
                else:
                    logger.info("Request user changed to %s at %s",
                                user, self.request.get_full_path())
                    self.request.user = user
                    self.request.token_user = True
        else:
            logger.debug("no token supplied to %s",
                         self.request.get_full_path())

        return super(TokenOperationView, self).check_auth()

    def validate_key(self, pk, key):
        """Get object based on signed token.
        """
        try:
            data = signing.loads(key, salt=self.get_salt())
            logger.debug('Token data: %s', unicode(data))
            instance, user = data
            logger.debug('Extracted token data: instance: %s, user: %s',
                         unicode(instance), unicode(user))
        except (signing.BadSignature, ValueError, TypeError) as e:
            logger.warning('Tried invalid token. Token: %s, user: %s. %s',
                           key, unicode(self.request.user), unicode(e))
            raise SuspiciousOperation()

        try:
            instance, user = signing.loads(key, max_age=self.token_max_age,
                                           salt=self.get_salt())
            logger.debug('Extracted non-expired token data: %s, %s',
                         unicode(instance), unicode(user))
        except signing.BadSignature as e:
            raise signing.SignatureExpired()

        if pk != instance:
            logger.debug('pk (%d) != instance (%d)', pk, instance)
            raise SuspiciousOperation()
        user = User.objects.get(pk=user)
        return user


class VmRenewView(FormOperationMixin, TokenOperationView, VmOperationView):
    op = 'renew'
    icon = 'calendar'
655
    effect = 'success'
Őry Máté committed
656 657 658
    show_in_toolbar = False
    form_class = VmRenewForm
    wait_for_result = 0.5
659 660
    template_name = 'dashboard/_vm-renew.html'
    with_reload = True
Őry Máté committed
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679

    def get_form_kwargs(self):
        choices = Lease.get_objects_with_level("user", self.request.user)
        default = self.get_op().instance.lease
        if default and default not in choices:
            choices = (choices.distinct() |
                       Lease.objects.filter(pk=default.pk).distinct())

        val = super(VmRenewView, self).get_form_kwargs()
        val.update({'choices': choices, 'default': default})
        return val

    def get_response_data(self, result, done, extra=None, **kwargs):
        extra = super(VmRenewView, self).get_response_data(result, done,
                                                           extra, **kwargs)
        extra["new_suspend_time"] = unicode(self.get_op().
                                            instance.time_of_suspend)
        return extra

680 681
    def get_context_data(self, **kwargs):
        context = super(VmRenewView, self).get_context_data(**kwargs)
682
        context['lease_request_form'] = LeaseRequestForm(request=self.request)
683
        context['lease_types'] = LeaseType.objects.exists()
684 685
        return context

Őry Máté committed
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

class VmStateChangeView(FormOperationMixin, VmOperationView):
    op = 'emergency_change_state'
    icon = 'legal'
    effect = 'danger'
    form_class = VmStateChangeForm
    wait_for_result = 0.5

    def get_form_kwargs(self):
        inst = self.get_op().instance
        active_activities = InstanceActivity.objects.filter(
            finished__isnull=True, instance=inst)
        show_interrupt = active_activities.exists()
        val = super(VmStateChangeView, self).get_form_kwargs()
        val.update({'show_interrupt': show_interrupt, 'status': inst.status})
        return val


704 705 706 707 708 709 710 711 712
class RedeployView(FormOperationMixin, VmOperationView):
    op = 'redeploy'
    icon = 'stethoscope'
    effect = 'danger'
    show_in_toolbar = True
    form_class = RedeployForm
    wait_for_result = 0.5


713 714 715 716 717 718 719
class VmDeployView(FormOperationMixin, VmOperationView):
    op = 'deploy'
    icon = 'play'
    effect = 'success'
    form_class = VmDeployForm

    def get_form_kwargs(self):
720
        kwargs = super(VmDeployView, self).get_form_kwargs()
721 722 723 724
        if self.request.user.is_superuser:
            online = (n.pk for n in
                      Node.objects.filter(enabled=True) if n.online)
            kwargs['choices'] = Node.objects.filter(pk__in=online)
725
            kwargs['instance'] = self.get_object()
726 727 728
        return kwargs


729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
class VmRenameView(FormOperationMixin, VmOperationView):
    op = 'rename'
    icon = 'pencil'
    effect = 'success'
    show_in_toolbar = False
    form_class = VmRenameForm

    def post(self, request, extra=None, *args, **kwargs):
        if extra is None:
            extra = {}
        form = self.form_class(self.request.POST, **self.get_form_kwargs())
        if form.is_valid():
            extra.update(form.cleaned_data)
            resp = super(FormOperationMixin, self).post(
                request, extra, *args, **kwargs)
744
            success_message = _('VM successfully renamed.')
745
            if request.is_ajax():
746
                return JsonResponse({'new_name': extra['new_name']})
747 748 749 750 751 752 753
            else:
                messages.success(request, success_message)
                return resp
        else:
            return self.get(request)


Őry Máté committed
754
vm_ops = OrderedDict([
755
    ('deploy', VmDeployView),
Őry Máté committed
756 757 758 759 760 761 762 763 764 765 766 767 768 769
    ('wake_up', VmOperationView.factory(
        op='wake_up', icon='sun-o', effect='success')),
    ('sleep', VmOperationView.factory(
        extra_bases=[TokenOperationView],
        op='sleep', icon='moon-o', effect='info')),
    ('migrate', VmMigrateView),
    ('save_as_template', VmSaveView),
    ('reboot', VmOperationView.factory(
        op='reboot', icon='refresh', effect='warning')),
    ('reset', VmOperationView.factory(
        op='reset', icon='bolt', effect='warning')),
    ('shutdown', VmOperationView.factory(
        op='shutdown', icon='power-off', effect='warning')),
    ('shut_off', VmOperationView.factory(
770
        op='shut_off', icon='plug', effect='warning')),
Őry Máté committed
771 772 773
    ('recover', VmOperationView.factory(
        op='recover', icon='medkit', effect='warning')),
    ('nostate', VmStateChangeView),
774
    ('redeploy', RedeployView),
Őry Máté committed
775 776 777 778
    ('destroy', VmOperationView.factory(
        extra_bases=[TokenOperationView],
        op='destroy', icon='times', effect='danger')),
    ('create_disk', VmCreateDiskView),
779
    ('import_disk', VmImportDiskView),
Őry Máté committed
780
    ('download_disk', VmDownloadDiskView),
781 782 783
    ('export_disk', VmDiskModifyView.factory(
        op='export_disk', form_class=VmDiskExportForm,
        icon='download', effect='info')),
784 785 786 787 788 789
    ('resize_disk', VmDiskModifyView.factory(
        op='resize_disk', form_class=VmDiskResizeForm,
        icon='arrows-alt', effect="warning")),
    ('remove_disk', VmDiskModifyView.factory(
        op='remove_disk', form_class=VmDiskRemoveForm,
        icon='times', effect="danger")),
Őry Máté committed
790
    ('add_interface', VmAddInterfaceView),
791
    ('remove_interface', VmRemoveInterfaceView),
792
    ('remove_port', VmPortRemoveView),
793
    ('add_port', VmPortAddView),
Őry Máté committed
794 795 796 797 798 799 800 801 802
    ('renew', VmRenewView),
    ('resources_change', VmResourcesChangeView),
    ('password_reset', VmOperationView.factory(
        op='password_reset', icon='unlock', effect='warning',
        show_in_toolbar=False, wait_for_result=0.5, with_reload=True)),
    ('mount_store', VmOperationView.factory(
        op='mount_store', icon='briefcase', effect='info',
        show_in_toolbar=False,
    )),
803 804 805 806
    ('install_keys', VmOperationView.factory(
        op='install_keys', icon='key', effect='info',
        show_in_toolbar=False,
    )),
807
    ('rename', VmRenameView),
Őry Máté committed
808 809 810 811 812 813 814
])


def _get_activity_icon(act):
    op = act.get_operation()
    if op and op.id in vm_ops:
        return vm_ops[op.id].icon
815
    elif split_activity_code(act.activity_code)[-1] == u'console-accessed':
816
        return "terminal"
Őry Máté committed
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    else:
        return "cog"


def _format_activities(acts):
    for i in acts:
        i.icon = _get_activity_icon(i)
    return acts


class MassOperationView(OperationView):
    template_name = 'dashboard/mass-operate.html'

    def check_auth(self):
        self.get_op().check_perms(self.request.user)
        for i in self.get_object():
            if not i.has_level(self.request.user, "user"):
                raise PermissionDenied(
                    "You have no user access to instance %d" % i.pk)

    @classmethod
    def get_urlname(cls):
        return 'dashboard.vm.mass-op.%s' % cls.op

    @classmethod
    def get_url(cls):
        return reverse("dashboard.vm.mass-op.%s" % cls.op)

    def get_op(self, instance=None):
        if instance:
            return getattr(instance, self.op)
        else:
            return Instance._ops[self.op]

    def get_context_data(self, **kwargs):
        ctx = super(MassOperationView, self).get_context_data(**kwargs)
        instances = self.get_object()
        ctx['instances'] = self._get_operable_instances(
            instances, self.request.user)
        ctx['vm_count'] = sum(1 for i in ctx['instances'] if not i.disabled)
        return ctx

    def _call_operations(self, extra):
        request = self.request
        user = request.user
        instances = self.get_object()
        for i in instances:
            try:
                self.get_op(i).async(user=user, **extra)
            except HumanReadableException as e:
                e.send_message(request)
            except Exception as e:
                # pre-existing errors should have been catched when the
                # confirmation dialog was constructed
                messages.error(request, _(
                    "Failed to execute %(op)s operation on "
                    "instance %(instance)s.") % {"op": self.name,
                                                 "instance": i})

    def get_object(self):
        vms = getattr(self.request, self.request.method).getlist("vm")
        return Instance.objects.filter(pk__in=vms)

    def _get_operable_instances(self, instances, user):
        for i in instances:
            try:
                op = self.get_op(i)
                op.check_auth(user)
                op.check_precond()
            except PermissionDenied as e:
                i.disabled = create_readable(
                    _("You are not permitted to execute %(op)s on instance "
                      "%(instance)s."), instance=i.pk, op=self.name)
                i.disabled_icon = "lock"
            except Exception as e:
                i.disabled = fetch_human_exception(e)
            else:
                i.disabled = None
        return instances

    def post(self, request, extra=None, *args, **kwargs):
        self.check_auth()
        if extra is None:
            extra = {}
901 902 903 904 905 906

        if hasattr(self, 'form_class'):
            form = self.form_class(self.request.POST, **self.get_form_kwargs())
            if form.is_valid():
                extra.update(form.cleaned_data)

Őry Máté committed
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
        self._call_operations(extra)
        if request.is_ajax():
            store = messages.get_messages(request)
            store.used = True
            return HttpResponse(
                json.dumps({'messages': [unicode(m) for m in store]}),
                content_type="application/json"
            )
        else:
            return redirect(reverse("dashboard.views.vm-list"))

    @classmethod
    def factory(cls, vm_op, extra_bases=(), **kwargs):
        return type(str(cls.__name__ + vm_op.op),
                    tuple(list(extra_bases) + [cls, vm_op]), kwargs)


class MassMigrationView(MassOperationView, VmMigrateView):
    template_name = 'dashboard/_vm-mass-migrate.html'


vm_mass_ops = OrderedDict([
    ('deploy', MassOperationView.factory(vm_ops['deploy'])),
    ('wake_up', MassOperationView.factory(vm_ops['wake_up'])),
    ('sleep', MassOperationView.factory(vm_ops['sleep'])),
    ('reboot', MassOperationView.factory(vm_ops['reboot'])),
    ('reset', MassOperationView.factory(vm_ops['reset'])),
    ('shut_off', MassOperationView.factory(vm_ops['shut_off'])),
    ('migrate', MassMigrationView),
    ('destroy', MassOperationView.factory(vm_ops['destroy'])),
])


class VmList(LoginRequiredMixin, FilterMixin, ListView):
    template_name = "dashboard/vm-list.html"
    allowed_filters = {
        'name': "name__icontains",
        'node': "node__name__icontains",
945
        'node_exact': "node__name",
Őry Máté committed
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
        'status': "status__iexact",
        'tags[]': "tags__name__in",
        'tags': "tags__name__in",  # for search string
        'owner': "owner__username",
        'template': "template__pk",
    }

    def get_context_data(self, *args, **kwargs):
        context = super(VmList, self).get_context_data(*args, **kwargs)
        context['ops'] = []
        for k, v in vm_mass_ops.iteritems():
            try:
                v.check_perms(user=self.request.user)
            except PermissionDenied:
                pass
            else:
                context['ops'].append(v)
        context['search_form'] = self.search_form
        context['show_acts_in_progress'] = self.object_list.count() < 100
        return context

    def get(self, *args, **kwargs):
        if self.request.is_ajax():
            return self._create_ajax_request()
        else:
            self.search_form = VmListSearchForm(self.request.GET)
            self.search_form.full_clean()
            return super(VmList, self).get(*args, **kwargs)

    def _create_ajax_request(self):
        if self.request.GET.get("compact") is not None:
            instances = Instance.get_objects_with_level(
                "user", self.request.user).filter(destroyed_at=None)
            statuses = {}
            for i in instances:
                statuses[i.pk] = {
                    'status': i.get_status_display(),
                    'icon': i.get_status_icon(),
                    'in_status_change': i.is_in_status_change(),
                }
                if self.request.user.is_superuser:
                    statuses[i.pk]['node'] = i.node.name if i.node else "-"
            return HttpResponse(json.dumps(statuses),
                                content_type="application/json")
        else:
            favs = Instance.objects.filter(
                favourite__user=self.request.user).values_list('pk', flat=True)
            instances = Instance.get_objects_with_level(
                'user', self.request.user).filter(
                destroyed_at=None).all()
            instances = [{
                'pk': i.pk,
998
                'url': reverse('dashboard.views.detail', args=[i.pk]),
Őry Máté committed
999 1000 1001 1002
                'name': i.name,
                'icon': i.get_status_icon(),
                'host': i.short_hostname,
                'status': i.get_status_display(),
1003 1004
                'owner': (i.owner.profile.get_display_name()
                          if i.owner != self.request.user else None),
Őry Máté committed
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
                'fav': i.pk in favs,
            } for i in instances]
            return HttpResponse(
                json.dumps(list(instances)),  # instances is ValuesQuerySet
                content_type="application/json",
            )

    def create_acl_queryset(self, model):
        queryset = super(VmList, self).create_acl_queryset(model)
        if not self.search_form.cleaned_data.get("include_deleted"):
            queryset = queryset.filter(destroyed_at=None)
        return queryset

    def get_queryset(self):
        logger.debug('VmList.get_queryset() called. User: %s',
                     unicode(self.request.user))
        queryset = self.create_acl_queryset(Instance)

        self.create_fake_get()
        sort = self.request.GET.get("sort")
        # remove "-" that means descending order
        # also check if the column name is valid
        if (sort and
1028
                (sort[1:] if sort[0] == "-" else sort)
Őry Máté committed
1029 1030 1031
                in [i.name for i in Instance._meta.fields] + ["pk"]):
            queryset = queryset.order_by(sort)

1032 1033
        filters, excludes = self.get_queryset_filters()
        return queryset.filter(**filters).exclude(**excludes).prefetch_related(
1034 1035
            "owner", "node", "owner__profile", "interface_set", "lease",
            "interface_set__host").distinct()
Őry Máté committed
1036 1037 1038 1039 1040 1041 1042 1043


class VmCreate(LoginRequiredMixin, TemplateView):
    form_class = VmCustomizeForm
    form = None

    def get_template_names(self):
        if self.request.is_ajax():
Bach Dániel committed
1044
            return ['dashboard/_modal.html']
Őry Máté committed
1045 1046 1047
        else:
            return ['dashboard/nojs-wrapper.html']

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    def get_template(self, request, pk):
        try:
            template = InstanceTemplate.objects.get(
                pk=int(pk))
        except (ValueError, InstanceTemplate.DoesNotExist):
            raise Http404()
        if not template.has_level(request.user, 'user'):
            raise PermissionDenied()

        return template

Őry Máté committed
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    def get(self, request, form=None, *args, **kwargs):
        if not request.user.has_perm('vm.create_vm'):
            raise PermissionDenied()

        if form is None:
            template_pk = request.GET.get("template")
        else:
            template_pk = form.template.pk

        if template_pk:
1069
            template = self.get_template(request, template_pk)
Őry Máté committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
            if form is None:
                form = self.form_class(user=request.user, template=template)
        else:
            templates = InstanceTemplate.get_objects_with_level(
                'user', request.user, disregard_superuser=True)

        context = self.get_context_data(**kwargs)
        if template_pk:
            context.update({
                'template': 'dashboard/_vm-create-2.html',
                'box_title': _('Customize VM'),
                'ajax_title': True,
                'vm_create_form': form,
                'template_o': template,
            })
        else:
            context.update({
                'template': 'dashboard/_vm-create-1.html',
                'box_title': _('Create a VM'),
                'ajax_title': True,
                'templates': templates.all(),
1091
                'template_access_types': TemplateAccessType.objects.exists(),
1092
                'form': TemplateRequestForm(request=request),
Őry Máté committed
1093 1094 1095
            })
        return self.render_to_response(context)

1096 1097 1098 1099
    def __create_normal(self, request, template, *args, **kwargs):
        instances = [Instance.create_from_template(
            template=template,
            owner=request.user)]
Őry Máté committed
1100 1101
        return self.__deploy(request, instances)

1102
    def __create_customized(self, request, template, *args, **kwargs):
Őry Máté committed
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
        user = request.user
        # no form yet, using POST directly:
        form = self.form_class(
            request.POST, user=request.user, template=template)
        if not form.is_valid():
            return self.get(request, form, *args, **kwargs)
        post = form.cleaned_data

        ikwargs = {
            'name': post['name'],
            'template': template,
            'owner': user,
        }
        amount = post.get("amount", 1)
        if request.user.has_perm('vm.set_resources'):
            networks = [InterfaceTemplate(vlan=l, managed=l.managed)
                        for l in post['networks']]

            ikwargs.update({
                'num_cores': post['cpu_count'],
                'ram_size': post['ram_size'],
                'priority': post['cpu_priority'],
                'max_ram_size': post['ram_size'],
                'networks': networks,
                'disks': list(template.disks.all()),
            })

        else:
            pass

        instances = Instance.mass_create_from_template(amount=amount,
                                                       **ikwargs)
        return self.__deploy(request, instances)

    def __deploy(self, request, instances, *args, **kwargs):
1138 1139
        # workaround EncodeError: dictionary changed size during iteration
        user = User.objects.get(pk=request.user.pk)
Őry Máté committed
1140
        for i in instances:
1141
            i.deploy.async(user=user)
Őry Máté committed
1142 1143 1144 1145 1146

        if len(instances) > 1:
            messages.success(request, ungettext_lazy(
                "Successfully created %(count)d VM.",  # this should not happen
                "Successfully created %(count)d VMs.", len(instances)) % {
1147
                                 'count': len(instances)})
Őry Máté committed
1148 1149 1150 1151 1152 1153 1154 1155 1156
            path = "%s?stype=owned" % reverse("dashboard.views.vm-list")
        else:
            messages.success(request, _("VM successfully created."))
            path = instances[0].get_absolute_url()

        if request.is_ajax():
            return HttpResponse(json.dumps({'redirect': path}),
                                content_type="application/json")
        else:
Őry Máté committed
1157
            return HttpResponseRedirect("%s#activity" % path)
Őry Máté committed
1158 1159 1160 1161 1162 1163 1164

    def post(self, request, *args, **kwargs):
        user = request.user

        if not request.user.has_perm('vm.create_vm'):
            raise PermissionDenied()

1165 1166
        template = self.get_template(request, request.POST.get("template"))

Őry Máté committed
1167 1168
        # limit chekcs
        try:
1169 1170
            instance_limit = user.profile.instance_limit
            template_instance_limit = user.profile.template_instance_limit
Őry Máté committed
1171 1172 1173 1174 1175 1176
        except Exception as e:
            logger.debug('No profile or instance limit: %s', e)
        else:
            try:
                amount = int(request.POST.get("amount", 1))
            except:
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
                # TODO this should definitely use a Form
                amount = instance_limit
            instances = Instance.active.filter(owner=user).count()
            template_instances = template.get_user_instances(user).count()

            logger.debug('current instance use: %d, limit: %d',
                         instances, instance_limit)
            logger.debug('current template instance use: %d, limit: %d',
                         template_instances, template_instance_limit)

            if instances + amount > instance_limit:
                return self._limit_exceeded(instance_limit, request)
            if template_instances + amount > template_instance_limit:
                return self._limit_exceeded(template_instance_limit, request)
Őry Máté committed
1191 1192 1193 1194 1195

        create_func = (self.__create_normal if
                       request.POST.get("customized") is None else
                       self.__create_customized)

1196
        return create_func(request, template, *args, **kwargs)
Őry Máté committed
1197

1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    def _limit_exceeded(self, limit, request):
        messages.error(request,
                       _('Instance limit (%d) exceeded.')
                       % limit)
        if request.is_ajax():
            return HttpResponse(json.dumps({'redirect': '/'}),
                                content_type="application/json")
        else:
            return redirect('/')

Őry Máté committed
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

@require_GET
def get_vm_screenshot(request, pk):
    instance = get_object_or_404(Instance, pk=pk)
    try:
        image = instance.screenshot(user=request.user).getvalue()
    except:
        # TODO handle this better
        raise Http404()

Bach Dániel committed
1218
    return HttpResponse(image, content_type="image/png")
Őry Máté committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269


class InstanceActivityDetail(CheckedDetailView):
    model = InstanceActivity
    context_object_name = 'instanceactivity'  # much simpler to mock object
    template_name = 'dashboard/instanceactivity_detail.html'

    def get_has_level(self):
        return self.object.instance.has_level

    def get_context_data(self, **kwargs):
        ctx = super(InstanceActivityDetail, self).get_context_data(**kwargs)
        ctx['activities'] = _format_activities(
            self.object.instance.get_activities(self.request.user))
        ctx['icon'] = _get_activity_icon(self.object)
        return ctx


@require_GET
def get_disk_download_status(request, pk):
    disk = Disk.objects.get(pk=pk)
    if not disk.get_appliance().has_level(request.user, 'owner'):
        raise PermissionDenied()

    return HttpResponse(
        json.dumps({
            'percentage': disk.get_download_percentage(),
            'failed': disk.failed
        }),
        content_type="application/json",
    )


class ClientCheck(LoginRequiredMixin, TemplateView):

    def get_template_names(self):
        if self.request.is_ajax():
            return ['dashboard/_modal.html']
        else:
            return ['dashboard/nojs-wrapper.html']

    def get_context_data(self, *args, **kwargs):
        context = super(ClientCheck, self).get_context_data(*args, **kwargs)
        context.update({
            'box_title': _('About CIRCLE Client'),
            'ajax_title': False,
            'client_download_url': settings.CLIENT_DOWNLOAD_URL,
            'template': "dashboard/_client-check.html",
            'instance': get_object_or_404(
                Instance, pk=self.request.GET.get('vm')),
        })
1270
        if not context['instance'].has_level(self.request.user, 'user'):
Őry Máté committed
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
            raise PermissionDenied()
        return context

    def post(self, request, *args, **kwargs):
        instance = get_object_or_404(Instance, pk=request.POST.get('vm'))
        if not instance.has_level(request.user, 'operator'):
            raise PermissionDenied()
        response = redirect(instance.get_absolute_url())
        response.set_cookie('downloaded_client', 'True', 365 * 24 * 60 * 60)
        return response


@require_GET
def vm_activity(request, pk):
    instance = Instance.objects.get(pk=pk)
    if not instance.has_level(request.user, 'user'):
        raise PermissionDenied()

    response = {}
    show_all = request.GET.get("show_all", "false") == "true"
    activities = _format_activities(
        instance.get_merged_activities(request.user))
    show_show_all = len(activities) > 10
    if not show_all:
        activities = activities[:10]

    response['connect_uri'] = instance.get_connect_uri()
    response['human_readable_status'] = instance.get_status_display()
    response['status'] = instance.status
    response['icon'] = instance.get_status_icon()
    latest = instance.get_latest_activity_in_progress()
1302 1303 1304
    response['is_new_state'] = (latest and
                                latest.resultant_state is not None and
                                instance.status != latest.resultant_state)
Őry Máté committed
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

    context = {
        'instance': instance,
        'activities': activities,
        'show_show_all': show_show_all,
        'ops': get_operations(instance, request.user),
    }

    response['activities'] = render_to_string(
        "dashboard/vm-detail/_activity-timeline.html",
1315
        context, request
Őry Máté committed
1316 1317 1318
    )
    response['ops'] = render_to_string(
        "dashboard/vm-detail/_operations.html",
1319
        context, request
Őry Máté committed
1320 1321 1322
    )
    response['disk_ops'] = render_to_string(
        "dashboard/vm-detail/_disk-operations.html",
1323
        context, request
Őry Máté committed
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    )

    return HttpResponse(
        json.dumps(response),
        content_type="application/json"
    )


class FavouriteView(TemplateView):

    def post(self, *args, **kwargs):
        user = self.request.user
        vm = Instance.objects.get(pk=self.request.POST.get("vm"))
        if not vm.has_level(user, 'user'):
            raise PermissionDenied()
        try:
            Favourite.objects.get(instance=vm, user=user).delete()
            return HttpResponse("Deleted.")
        except Favourite.DoesNotExist:
            Favourite(instance=vm, user=user).save()
            return HttpResponse("Added.")


1347 1348
class TransferInstanceOwnershipConfirmView(TransferOwnershipConfirmView):
    template = "dashboard/confirm/transfer-instance-ownership.html"
Őry Máté committed
1349 1350
    model = Instance

1351 1352
    def change_owner(self, instance, new_owner):
        with instance.activity(
1353
                code_suffix='ownership-transferred',
1354 1355 1356 1357
                readable_name=ugettext_noop("transfer ownership"),
                concurrency_check=False, user=new_owner):
            super(TransferInstanceOwnershipConfirmView, self).change_owner(
                instance, new_owner)
Őry Máté committed
1358 1359


1360 1361 1362 1363
class TransferInstanceOwnershipView(TransferOwnershipView):
    confirm_view = TransferInstanceOwnershipConfirmView
    model = Instance
    notification_msg = ugettext_noop(
1364
        '%(owner)s offered you to take the ownership of '
1365 1366 1367 1368 1369
        'his/her virtual machine called %(instance)s. '
        '<a href="%(token)s" '
        'class="btn btn-success btn-small">Accept</a>')
    token_url = 'dashboard.views.vm-transfer-ownership-confirm'
    template = "dashboard/vm-detail/tx-owner.html"
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379


@login_required
def toggle_template_tutorial(request, pk):
    hidden = request.POST.get("hidden", "").lower() == "true"
    instance = get_object_or_404(Instance, pk=pk)
    response = HttpResponseRedirect(instance.get_absolute_url())
    response.set_cookie(  # for a week
        "hide_tutorial_for_%s" % pk, hidden, 7 * 24 * 60 * 60)
    return response