operations.py 28.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 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/>.

18
from __future__ import absolute_import, unicode_literals
Dudás Ádám committed
19
from logging import getLogger
20
from re import search
Őry Máté committed
21
from string import ascii_lowercase
Dudás Ádám committed
22

23
from django.core.exceptions import PermissionDenied
Dudás Ádám committed
24
from django.utils import timezone
25
from django.utils.translation import ugettext_lazy as _, ugettext_noop
Dudás Ádám committed
26

27 28
from sizefield.utils import filesizeformat

Dudás Ádám committed
29
from celery.exceptions import TimeLimitExceeded
30

31
from common.models import create_readable, humanize_exception
32
from common.operations import Operation, register_operation
33 34 35
from .tasks.local_tasks import (
    abortable_async_instance_operation, abortable_async_node_operation,
)
36
from .models import (
37
    Instance, InstanceActivity, InstanceTemplate, Interface, Node,
38
    NodeActivity, pwgen
39
)
40
from .tasks import agent_tasks
Dudás Ádám committed
41 42

logger = getLogger(__name__)
43 44


45
class InstanceOperation(Operation):
46
    acl_level = 'owner'
47
    async_operation = abortable_async_instance_operation
48
    host_cls = Instance
49
    concurrency_check = True
50 51
    accept_states = None
    deny_states = None
Dudás Ádám committed
52

53
    def __init__(self, instance):
54
        super(InstanceOperation, self).__init__(subject=instance)
55 56 57
        self.instance = instance

    def check_precond(self):
58 59
        if self.instance.destroyed_at:
            raise self.instance.InstanceDestroyedError(self.instance)
60 61 62 63 64 65 66 67 68 69 70 71 72 73
        if self.accept_states:
            if self.instance.status not in self.accept_states:
                logger.debug("precond failed for %s: %s not in %s",
                             unicode(self.__class__),
                             unicode(self.instance.status),
                             unicode(self.accept_states))
                raise self.instance.WrongStateError(self.instance)
        if self.deny_states:
            if self.instance.status in self.deny_states:
                logger.debug("precond failed for %s: %s in %s",
                             unicode(self.__class__),
                             unicode(self.instance.status),
                             unicode(self.accept_states))
                raise self.instance.WrongStateError(self.instance)
74 75

    def check_auth(self, user):
76
        if not self.instance.has_level(user, self.acl_level):
77 78 79
            raise humanize_exception(ugettext_noop(
                "%(acl_level)s level is required for this operation."),
                PermissionDenied(), acl_level=self.acl_level)
80

81
        super(InstanceOperation, self).check_auth(user=user)
82

83 84
    def create_activity(self, parent, user, kwargs):
        name = self.get_activity_name(kwargs)
85 86 87 88 89 90 91 92 93 94
        if parent:
            if parent.instance != self.instance:
                raise ValueError("The instance associated with the specified "
                                 "parent activity does not match the instance "
                                 "bound to the operation.")
            if parent.user != user:
                raise ValueError("The user associated with the specified "
                                 "parent activity does not match the user "
                                 "provided as parameter.")

95 96
            return parent.create_sub(code_suffix=self.activity_code_suffix,
                                     readable_name=name)
97 98 99
        else:
            return InstanceActivity.create(
                code_suffix=self.activity_code_suffix, instance=self.instance,
100 101
                readable_name=name, user=user,
                concurrency_check=self.concurrency_check)
102

103 104 105 106 107
    def is_preferred(self):
        """If this is the recommended op in the current state of the instance.
        """
        return False

108

109 110 111 112 113 114
class AddInterfaceOperation(InstanceOperation):
    activity_code_suffix = 'add_interface'
    id = 'add_interface'
    name = _("add interface")
    description = _("Add a new network interface for the specified VLAN to "
                    "the VM.")
115
    required_perms = ()
116
    accept_states = ('STOPPED', 'PENDING', 'RUNNING')
117

118 119 120 121 122 123 124
    def rollback(self, net, activity):
        with activity.sub_activity(
            'destroying_net',
                readable_name=ugettext_noop("destroy network (rollback)")):
            net.destroy()
            net.delete()

125
    def _operation(self, activity, user, system, vlan, managed=None):
126
        if not vlan.has_level(user, 'user'):
127 128 129
            raise humanize_exception(ugettext_noop(
                "User acces to vlan %(vlan)s is required."),
                PermissionDenied(), vlan=vlan)
130 131 132 133 134 135 136
        if managed is None:
            managed = vlan.managed

        net = Interface.create(base_activity=activity, instance=self.instance,
                               managed=managed, owner=user, vlan=vlan)

        if self.instance.is_running:
137
            try:
138 139 140
                with activity.sub_activity(
                    'attach_network',
                        readable_name=ugettext_noop("attach network")):
141 142 143 144 145
                    self.instance.attach_network(net)
            except Exception as e:
                if hasattr(e, 'libvirtError'):
                    self.rollback(net, activity)
                raise
146 147
            net.deploy()

148 149 150 151
    def get_activity_name(self, kwargs):
        return create_readable(ugettext_noop("add %(vlan)s interface"),
                               vlan=kwargs['vlan'])

152

Bach Dániel committed
153
register_operation(AddInterfaceOperation)
154 155


156
class CreateDiskOperation(InstanceOperation):
157

158 159 160 161
    activity_code_suffix = 'create_disk'
    id = 'create_disk'
    name = _("create disk")
    description = _("Create empty disk for the VM.")
162
    required_perms = ('storage.create_empty_disk', )
163
    accept_states = ('STOPPED', 'PENDING', 'RUNNING')
164

165
    def _operation(self, user, size, activity, name=None):
Bach Dániel committed
166 167
        from storage.models import Disk

168 169 170
        if not name:
            name = "new disk"
        disk = Disk.create(size=size, name=name, type="qcow2-norm")
171
        disk.full_clean()
172 173 174 175
        devnums = list(ascii_lowercase)
        for d in self.instance.disks.all():
            devnums.remove(d.dev_num)
        disk.dev_num = devnums.pop(0)
176
        disk.save()
177 178
        self.instance.disks.add(disk)

179
        if self.instance.is_running:
180 181 182 183
            with activity.sub_activity(
                'deploying_disk',
                readable_name=ugettext_noop("deploying disk")
            ):
184
                disk.deploy()
185 186 187 188
            with activity.sub_activity(
                'attach_disk',
                readable_name=ugettext_noop("attach disk")
            ):
189 190
                self.instance.attach_disk(disk)

191
    def get_activity_name(self, kwargs):
192 193 194
        return create_readable(
            ugettext_noop("create disk %(name)s (%(size)s)"),
            size=filesizeformat(kwargs['size']), name=kwargs['name'])
195 196


197 198 199 200 201 202 203 204 205
register_operation(CreateDiskOperation)


class DownloadDiskOperation(InstanceOperation):
    activity_code_suffix = 'download_disk'
    id = 'download_disk'
    name = _("download disk")
    description = _("Download disk for the VM.")
    abortable = True
206
    has_percentage = True
207
    required_perms = ('storage.download_disk', )
208
    accept_states = ('STOPPED', 'PENDING', 'RUNNING')
209

210 211
    def _operation(self, user, url, task, activity, name=None):
        activity.result = url
Bach Dániel committed
212 213
        from storage.models import Disk

214
        disk = Disk.download(url=url, name=name, task=task)
215 216 217 218
        devnums = list(ascii_lowercase)
        for d in self.instance.disks.all():
            devnums.remove(d.dev_num)
        disk.dev_num = devnums.pop(0)
219
        disk.full_clean()
220
        disk.save()
221
        self.instance.disks.add(disk)
222 223
        activity.readable_name = create_readable(
            ugettext_noop("download %(name)s"), name=disk.name)
224

Őry Máté committed
225
        # TODO iso (cd) hot-plug is not supported by kvm/guests
226
        if self.instance.is_running and disk.type not in ["iso"]:
227 228 229 230
            with activity.sub_activity(
                'attach_disk',
                readable_name=ugettext_noop("attach disk")
            ):
231 232
                self.instance.attach_disk(disk)

233 234 235
register_operation(DownloadDiskOperation)


236
class DeployOperation(InstanceOperation):
Dudás Ádám committed
237 238 239
    activity_code_suffix = 'deploy'
    id = 'deploy'
    name = _("deploy")
240
    description = _("Deploy new virtual machine with network.")
241
    required_perms = ()
242
    deny_states = ('SUSPENDED', 'RUNNING')
Dudás Ádám committed
243

244 245
    def is_preferred(self):
        return self.instance.status in (self.instance.STATUS.STOPPED,
246
                                        self.instance.STATUS.PENDING,
247 248
                                        self.instance.STATUS.ERROR)

Dudás Ádám committed
249 250 251
    def on_commit(self, activity):
        activity.resultant_state = 'RUNNING'

252
    def _operation(self, activity, timeout=15):
Dudás Ádám committed
253 254 255
        # Allocate VNC port and host node
        self.instance.allocate_vnc_port()
        self.instance.allocate_node()
Dudás Ádám committed
256 257

        # Deploy virtual images
258 259 260
        with activity.sub_activity(
            'deploying_disks', readable_name=ugettext_noop(
                "deploy disks")):
Dudás Ádám committed
261 262 263
            self.instance.deploy_disks()

        # Deploy VM on remote machine
264
        if self.instance.state not in ['PAUSED']:
265 266 267
            with activity.sub_activity(
                'deploying_vm', readable_name=ugettext_noop(
                    "deploy virtual machine")) as deploy_act:
268
                deploy_act.result = self.instance.deploy_vm(timeout=timeout)
Dudás Ádám committed
269 270

        # Establish network connection (vmdriver)
271 272 273
        with activity.sub_activity(
            'deploying_net', readable_name=ugettext_noop(
                "deploy network")):
Dudás Ádám committed
274 275 276
            self.instance.deploy_net()

        # Resume vm
277 278 279
        with activity.sub_activity(
            'booting', readable_name=ugettext_noop(
                "boot virtual machine")):
Dudás Ádám committed
280
            self.instance.resume_vm(timeout=timeout)
Dudás Ádám committed
281

282
        self.instance.renew(parent_activity=activity)
Dudás Ádám committed
283 284


285
register_operation(DeployOperation)
Dudás Ádám committed
286 287


288
class DestroyOperation(InstanceOperation):
Dudás Ádám committed
289 290 291
    activity_code_suffix = 'destroy'
    id = 'destroy'
    name = _("destroy")
292
    description = _("Destroy virtual machine and its networks.")
293
    required_perms = ()
Dudás Ádám committed
294 295 296 297

    def on_commit(self, activity):
        activity.resultant_state = 'DESTROYED'

298
    def _operation(self, activity):
299
        # Destroy networks
300 301 302
        with activity.sub_activity(
                'destroying_net',
                readable_name=ugettext_noop("destroy network")):
303
            if self.instance.node:
304
                self.instance.shutdown_net()
305
            self.instance.destroy_net()
Dudás Ádám committed
306

307
        if self.instance.node:
Dudás Ádám committed
308
            # Delete virtual machine
309 310 311
            with activity.sub_activity(
                    'destroying_vm',
                    readable_name=ugettext_noop("destroy virtual machine")):
Dudás Ádám committed
312
                self.instance.delete_vm()
Dudás Ádám committed
313 314

        # Destroy disks
315 316 317
        with activity.sub_activity(
                'destroying_disks',
                readable_name=ugettext_noop("destroy disks")):
Dudás Ádám committed
318
            self.instance.destroy_disks()
Dudás Ádám committed
319

Dudás Ádám committed
320 321 322 323 324 325 326 327 328
        # Delete mem. dump if exists
        try:
            self.instance.delete_mem_dump()
        except:
            pass

        # Clear node and VNC port association
        self.instance.yield_node()
        self.instance.yield_vnc_port()
Dudás Ádám committed
329 330 331 332 333

        self.instance.destroyed_at = timezone.now()
        self.instance.save()


334
register_operation(DestroyOperation)
Dudás Ádám committed
335 336


337
class MigrateOperation(InstanceOperation):
Dudás Ádám committed
338 339 340
    activity_code_suffix = 'migrate'
    id = 'migrate'
    name = _("migrate")
341
    description = _("Live migrate running VM to another node.")
342
    required_perms = ()
343
    accept_states = ('RUNNING', )
Dudás Ádám committed
344

345
    def rollback(self, activity):
346 347 348
        with activity.sub_activity(
            'rollback_net', readable_name=ugettext_noop(
                "redeploy network (rollback)")):
349 350
            self.instance.deploy_net()

351 352 353 354 355 356
    def check_auth(self, user):
        if not user.is_superuser:
            raise PermissionDenied()

        super(MigrateOperation, self).check_auth(user=user)

357
    def _operation(self, activity, to_node=None, timeout=120):
Dudás Ádám committed
358
        if not to_node:
359 360 361
            with activity.sub_activity('scheduling',
                                       readable_name=ugettext_noop(
                                           "schedule")) as sa:
Dudás Ádám committed
362 363 364
                to_node = self.instance.select_node()
                sa.result = to_node

365
        try:
366 367 368
            with activity.sub_activity(
                'migrate_vm', readable_name=create_readable(
                    ugettext_noop("migrate to %(node)s"), node=to_node)):
369 370 371 372
                self.instance.migrate_vm(to_node=to_node, timeout=timeout)
        except Exception as e:
            if hasattr(e, 'libvirtError'):
                self.rollback(activity)
Bach Dániel committed
373
            raise
Dudás Ádám committed
374

375
        # Shutdown networks
376 377 378
        with activity.sub_activity(
            'shutdown_net', readable_name=ugettext_noop(
                "shutdown network")):
379 380
            self.instance.shutdown_net()

Dudás Ádám committed
381 382 383 384
        # Refresh node information
        self.instance.node = to_node
        self.instance.save()
        # Estabilish network connection (vmdriver)
385 386 387
        with activity.sub_activity(
            'deploying_net', readable_name=ugettext_noop(
                "deploy network")):
Dudás Ádám committed
388
            self.instance.deploy_net()
Dudás Ádám committed
389 390


391
register_operation(MigrateOperation)
Dudás Ádám committed
392 393


394
class RebootOperation(InstanceOperation):
Dudás Ádám committed
395 396 397
    activity_code_suffix = 'reboot'
    id = 'reboot'
    name = _("reboot")
398
    description = _("Reboot virtual machine with Ctrl+Alt+Del signal.")
399
    required_perms = ()
400
    accept_states = ('RUNNING', )
Dudás Ádám committed
401

402
    def _operation(self, timeout=5):
Dudás Ádám committed
403
        self.instance.reboot_vm(timeout=timeout)
Dudás Ádám committed
404 405


406
register_operation(RebootOperation)
Dudás Ádám committed
407 408


409 410 411 412 413
class RemoveInterfaceOperation(InstanceOperation):
    activity_code_suffix = 'remove_interface'
    id = 'remove_interface'
    name = _("remove interface")
    description = _("Remove the specified network interface from the VM.")
414
    required_perms = ()
415
    accept_states = ('STOPPED', 'PENDING', 'RUNNING')
416

417 418
    def _operation(self, activity, user, system, interface):
        if self.instance.is_running:
419 420 421 422
            with activity.sub_activity(
                'detach_network',
                readable_name=ugettext_noop("detach network")
            ):
423
                self.instance.detach_network(interface)
424 425 426 427 428
            interface.shutdown()

        interface.destroy()
        interface.delete()

429 430
    def get_activity_name(self, kwargs):
        return create_readable(ugettext_noop("remove %(vlan)s interface"),
431
                               vlan=kwargs['interface'].vlan)
432

433

Bach Dániel committed
434
register_operation(RemoveInterfaceOperation)
435 436


437 438 439 440 441
class RemoveDiskOperation(InstanceOperation):
    activity_code_suffix = 'remove_disk'
    id = 'remove_disk'
    name = _("remove disk")
    description = _("Remove the specified disk from the VM.")
442
    required_perms = ()
443
    accept_states = ('STOPPED', 'PENDING', 'RUNNING')
444 445

    def _operation(self, activity, user, system, disk):
446
        if self.instance.is_running and disk.type not in ["iso"]:
447 448 449 450
            with activity.sub_activity(
                'detach_disk',
                readable_name=ugettext_noop('detach disk')
            ):
451
                self.instance.detach_disk(disk)
452 453 454 455 456
        with activity.sub_activity(
            'destroy_disk',
            readable_name=ugettext_noop('destroy disk')
        ):
            return self.instance.disks.remove(disk)
457

458 459 460
    def get_activity_name(self, kwargs):
        return create_readable(ugettext_noop('remove disk %(name)s'),
                               name=kwargs["disk"].name)
461

Guba Sándor committed
462
register_operation(RemoveDiskOperation)
463 464


465
class ResetOperation(InstanceOperation):
Dudás Ádám committed
466 467 468
    activity_code_suffix = 'reset'
    id = 'reset'
    name = _("reset")
469
    description = _("Reset virtual machine (reset button).")
470
    required_perms = ()
471
    accept_states = ('RUNNING', )
Dudás Ádám committed
472

473
    def _operation(self, timeout=5):
Dudás Ádám committed
474
        self.instance.reset_vm(timeout=timeout)
Dudás Ádám committed
475

476
register_operation(ResetOperation)
Dudás Ádám committed
477 478


479
class SaveAsTemplateOperation(InstanceOperation):
Dudás Ádám committed
480 481 482 483 484 485 486 487
    activity_code_suffix = 'save_as_template'
    id = 'save_as_template'
    name = _("save as template")
    description = _("""Save Virtual Machine as a Template.

        Template can be shared with groups and users.
        Users can instantiate Virtual Machines from Templates.
        """)
488
    abortable = True
489
    required_perms = ('vm.create_template', )
490
    accept_states = ('RUNNING', 'PENDING', 'STOPPED')
Dudás Ádám committed
491

492 493 494 495
    def is_preferred(self):
        return (self.instance.is_base and
                self.instance.status == self.instance.STATUS.RUNNING)

496 497 498 499 500 501
    @staticmethod
    def _rename(name):
        m = search(r" v(\d+)$", name)
        if m:
            v = int(m.group(1)) + 1
            name = search(r"^(.*) v(\d+)$", name).group(1)
502
        else:
503 504
            v = 1
        return "%s v%d" % (name, v)
505

506
    def on_abort(self, activity, error):
507
        if hasattr(self, 'disks'):
508 509 510
            for disk in self.disks:
                disk.destroy()

511
    def _operation(self, activity, user, system, timeout=300, name=None,
512
                   with_shutdown=True, task=None, **kwargs):
513
        if with_shutdown:
514 515
            try:
                ShutdownOperation(self.instance).call(parent_activity=activity,
516
                                                      user=user, task=task)
517 518 519
            except Instance.WrongStateError:
                pass

Dudás Ádám committed
520 521 522 523 524 525 526 527
        # prepare parameters
        params = {
            'access_method': self.instance.access_method,
            'arch': self.instance.arch,
            'boot_menu': self.instance.boot_menu,
            'description': self.instance.description,
            'lease': self.instance.lease,  # Can be problem in new VM
            'max_ram_size': self.instance.max_ram_size,
528
            'name': name or self._rename(self.instance.name),
Dudás Ádám committed
529 530 531 532 533 534 535 536 537
            'num_cores': self.instance.num_cores,
            'owner': user,
            'parent': self.instance.template,  # Can be problem
            'priority': self.instance.priority,
            'ram_size': self.instance.ram_size,
            'raw_data': self.instance.raw_data,
            'system': self.instance.system,
        }
        params.update(kwargs)
Bach Dániel committed
538
        params.pop("parent_activity", None)
Dudás Ádám committed
539

540 541
        from storage.models import Disk

Dudás Ádám committed
542 543
        def __try_save_disk(disk):
            try:
544
                return disk.save_as(task)
Dudás Ádám committed
545 546 547
            except Disk.WrongDiskTypeError:
                return disk

548
        self.disks = []
549 550 551 552 553 554 555
        for disk in self.instance.disks.all():
            with activity.sub_activity(
                'saving_disk',
                readable_name=create_readable(
                    ugettext_noop("saving disk %(name)s"),
                    name=disk.name)
            ):
556 557
                self.disks.append(__try_save_disk(disk))

Dudás Ádám committed
558 559 560 561 562
        # create template and do additional setup
        tmpl = InstanceTemplate(**params)
        tmpl.full_clean()  # Avoiding database errors.
        tmpl.save()
        try:
563
            tmpl.disks.add(*self.disks)
Dudás Ádám committed
564 565 566 567 568 569 570 571 572 573
            # create interface templates
            for i in self.instance.interface_set.all():
                i.save_as_template(tmpl)
        except:
            tmpl.delete()
            raise
        else:
            return tmpl


574
register_operation(SaveAsTemplateOperation)
Dudás Ádám committed
575 576


577
class ShutdownOperation(InstanceOperation):
Dudás Ádám committed
578 579 580
    activity_code_suffix = 'shutdown'
    id = 'shutdown'
    name = _("shutdown")
581
    description = _("Shutdown virtual machine with ACPI signal.")
Kálmán Viktor committed
582
    abortable = True
583
    required_perms = ()
584
    accept_states = ('RUNNING', )
585

Dudás Ádám committed
586 587 588
    def on_commit(self, activity):
        activity.resultant_state = 'STOPPED'

589 590
    def _operation(self, task=None):
        self.instance.shutdown_vm(task=task)
Dudás Ádám committed
591 592
        self.instance.yield_node()
        self.instance.yield_vnc_port()
Dudás Ádám committed
593 594


595
register_operation(ShutdownOperation)
Dudás Ádám committed
596 597


598
class ShutOffOperation(InstanceOperation):
Dudás Ádám committed
599 600 601
    activity_code_suffix = 'shut_off'
    id = 'shut_off'
    name = _("shut off")
602
    description = _("Shut off VM (plug-out).")
603
    required_perms = ()
604
    accept_states = ('RUNNING', )
Dudás Ádám committed
605

606
    def on_commit(self, activity):
Dudás Ádám committed
607 608
        activity.resultant_state = 'STOPPED'

609
    def _operation(self, activity):
Dudás Ádám committed
610 611 612
        # Shutdown networks
        with activity.sub_activity('shutdown_net'):
            self.instance.shutdown_net()
Dudás Ádám committed
613

Dudás Ádám committed
614 615 616 617 618 619 620
        # Delete virtual machine
        with activity.sub_activity('delete_vm'):
            self.instance.delete_vm()

        # Clear node and VNC port association
        self.instance.yield_node()
        self.instance.yield_vnc_port()
Dudás Ádám committed
621 622


623
register_operation(ShutOffOperation)
Dudás Ádám committed
624 625


626
class SleepOperation(InstanceOperation):
Dudás Ádám committed
627 628 629
    activity_code_suffix = 'sleep'
    id = 'sleep'
    name = _("sleep")
630
    description = _("Suspend virtual machine with memory dump.")
631
    required_perms = ()
632
    accept_states = ('RUNNING', )
Dudás Ádám committed
633

634 635 636 637
    def is_preferred(self):
        return (not self.instance.is_base and
                self.instance.status == self.instance.STATUS.RUNNING)

Dudás Ádám committed
638 639 640 641 642 643 644 645 646
    def on_abort(self, activity, error):
        if isinstance(error, TimeLimitExceeded):
            activity.resultant_state = None
        else:
            activity.resultant_state = 'ERROR'

    def on_commit(self, activity):
        activity.resultant_state = 'SUSPENDED'

647
    def _operation(self, activity, timeout=240):
Dudás Ádám committed
648
        # Destroy networks
649 650
        with activity.sub_activity('shutdown_net', readable_name=ugettext_noop(
                "shutdown network")):
Dudás Ádám committed
651
            self.instance.shutdown_net()
Dudás Ádám committed
652 653

        # Suspend vm
654 655 656
        with activity.sub_activity('suspending',
                                   readable_name=ugettext_noop(
                                       "suspend virtual machine")):
Dudás Ádám committed
657 658 659 660
            self.instance.suspend_vm(timeout=timeout)

        self.instance.yield_node()
        # VNC port needs to be kept
Dudás Ádám committed
661 662


663
register_operation(SleepOperation)
Dudás Ádám committed
664 665


666
class WakeUpOperation(InstanceOperation):
Dudás Ádám committed
667 668 669 670 671 672 673
    activity_code_suffix = 'wake_up'
    id = 'wake_up'
    name = _("wake up")
    description = _("""Wake up Virtual Machine from SUSPENDED state.

        Power on Virtual Machine and load its memory from dump.
        """)
674
    required_perms = ()
675
    accept_states = ('SUSPENDED', )
Dudás Ádám committed
676

677
    def is_preferred(self):
678
        return self.instance.status == self.instance.STATUS.SUSPENDED
679

Dudás Ádám committed
680 681 682 683 684 685
    def on_abort(self, activity, error):
        activity.resultant_state = 'ERROR'

    def on_commit(self, activity):
        activity.resultant_state = 'RUNNING'

686
    def _operation(self, activity, timeout=60):
Dudás Ádám committed
687
        # Schedule vm
Dudás Ádám committed
688 689
        self.instance.allocate_vnc_port()
        self.instance.allocate_node()
Dudás Ádám committed
690 691

        # Resume vm
692 693 694
        with activity.sub_activity(
            'resuming', readable_name=ugettext_noop(
                "resume virtual machine")):
Dudás Ádám committed
695
            self.instance.wake_up_vm(timeout=timeout)
Dudás Ádám committed
696 697

        # Estabilish network connection (vmdriver)
698 699 700
        with activity.sub_activity(
            'deploying_net', readable_name=ugettext_noop(
                "deploy network")):
Dudás Ádám committed
701
            self.instance.deploy_net()
Dudás Ádám committed
702 703

        # Renew vm
704
        self.instance.renew(parent_activity=activity)
Dudás Ádám committed
705 706


707
register_operation(WakeUpOperation)
708 709


710 711 712 713 714 715
class RenewOperation(InstanceOperation):
    activity_code_suffix = 'renew'
    id = 'renew'
    name = _("renew")
    description = _("Renew expiration times")
    acl_level = "operator"
716
    required_perms = ()
717
    concurrency_check = False
718 719 720 721

    def _operation(self, lease=None):
        (self.instance.time_of_suspend,
         self.instance.time_of_delete) = self.instance.get_renew_times(lease)
722
        self.instance.save()
723 724 725 726 727


register_operation(RenewOperation)


728
class ChangeStateOperation(InstanceOperation):
Guba Sándor committed
729 730 731
    activity_code_suffix = 'emergency_change_state'
    id = 'emergency_change_state'
    name = _("emergency change state")
732 733
    description = _("Change the virtual machine state to NOSTATE")
    acl_level = "owner"
Guba Sándor committed
734
    required_perms = ('vm.emergency_change_state', )
735

Guba Sándor committed
736
    def _operation(self, user, activity, new_state="NOSTATE"):
737 738 739 740 741 742
        activity.resultant_state = new_state


register_operation(ChangeStateOperation)


743
class NodeOperation(Operation):
744
    async_operation = abortable_async_node_operation
745
    host_cls = Node
746 747 748 749 750

    def __init__(self, node):
        super(NodeOperation, self).__init__(subject=node)
        self.node = node

751 752
    def create_activity(self, parent, user, kwargs):
        name = self.get_activity_name(kwargs)
753 754 755 756 757 758 759 760 761 762
        if parent:
            if parent.node != self.node:
                raise ValueError("The node associated with the specified "
                                 "parent activity does not match the node "
                                 "bound to the operation.")
            if parent.user != user:
                raise ValueError("The user associated with the specified "
                                 "parent activity does not match the user "
                                 "provided as parameter.")

763 764
            return parent.create_sub(code_suffix=self.activity_code_suffix,
                                     readable_name=name)
765 766
        else:
            return NodeActivity.create(code_suffix=self.activity_code_suffix,
767 768
                                       node=self.node, user=user,
                                       readable_name=name)
769 770 771 772 773 774


class FlushOperation(NodeOperation):
    activity_code_suffix = 'flush'
    id = 'flush'
    name = _("flush")
775
    description = _("Disable node and move all instances to other ones.")
776
    required_perms = ()
777

778 779 780 781 782 783
    def on_abort(self, activity, error):
        from manager.scheduler import TraitsUnsatisfiableException
        if isinstance(error, TraitsUnsatisfiableException):
            if self.node_enabled:
                self.node.enable(activity.user, activity)

784 785
    def check_auth(self, user):
        if not user.is_superuser:
786 787
            raise humanize_exception(ugettext_noop(
                "Superuser privileges are required."), PermissionDenied())
788 789 790

        super(FlushOperation, self).check_auth(user=user)

791
    def _operation(self, activity, user):
792
        self.node_enabled = self.node.enabled
793 794
        self.node.disable(user, activity)
        for i in self.node.instance_set.all():
795 796 797 798
            name = create_readable(ugettext_noop(
                "migrate %(instance)s (%(pk)s)"), instance=i.name, pk=i.pk)
            with activity.sub_activity('migrate_instance_%d' % i.pk,
                                       readable_name=name):
Bach Dániel committed
799
                i.migrate(user=user)
800 801


802
register_operation(FlushOperation)
803 804 805 806 807 808 809 810


class ScreenshotOperation(InstanceOperation):
    activity_code_suffix = 'screenshot'
    id = 'screenshot'
    name = _("screenshot")
    description = _("Get screenshot")
    acl_level = "owner"
811
    required_perms = ()
812
    accept_states = ('RUNNING', )
813

Kálmán Viktor committed
814
    def _operation(self):
815 816 817 818
        return self.instance.get_screenshot(timeout=20)


register_operation(ScreenshotOperation)
Bach Dániel committed
819 820 821 822 823 824 825 826 827


class RecoverOperation(InstanceOperation):
    activity_code_suffix = 'recover'
    id = 'recover'
    name = _("recover")
    description = _("Recover virtual machine from destroyed state.")
    acl_level = "owner"
    required_perms = ('vm.recover', )
828
    accept_states = ('DESTROYED', )
Bach Dániel committed
829 830

    def check_precond(self):
831 832 833 834
        try:
            super(RecoverOperation, self).check_precond()
        except Instance.InstanceDestroyedError:
            pass
Bach Dániel committed
835 836 837 838 839 840 841 842 843 844 845 846 847 848

    def on_commit(self, activity):
        activity.resultant_state = 'PENDING'

    def _operation(self):
        for disk in self.instance.disks.all():
            disk.destroyed = None
            disk.restore()
            disk.save()
        self.instance.destroyed_at = None
        self.instance.save()


register_operation(RecoverOperation)
849 850


851 852 853 854 855 856
class ResourcesOperation(InstanceOperation):
    activity_code_suffix = 'Resources change'
    id = 'resources_change'
    name = _("resources change")
    description = _("Change resources")
    acl_level = "owner"
857
    required_perms = ('vm.change_resources', )
858
    accept_states = ('STOPPED', 'PENDING', )
859

860 861
    def _operation(self, user, num_cores, ram_size, max_ram_size, priority):

862 863 864 865 866
        self.instance.num_cores = num_cores
        self.instance.ram_size = ram_size
        self.instance.max_ram_size = max_ram_size
        self.instance.priority = priority

867
        self.instance.full_clean()
868 869 870 871
        self.instance.save()


register_operation(ResourcesOperation)
872 873 874 875 876 877 878 879 880


class PasswordResetOperation(InstanceOperation):
    activity_code_suffix = 'Password reset'
    id = 'password_reset'
    name = _("password reset")
    description = _("Password reset")
    acl_level = "owner"
    required_perms = ()
881
    accept_states = ('RUNNING', )
882 883

    def _operation(self):
884 885 886 887 888
        self.instance.pw = pwgen()
        queue = self.instance.get_remote_queue_name("agent")
        agent_tasks.change_password.apply_async(
            queue=queue, args=(self.instance.vm_name, self.instance.pw))
        self.instance.save()
889 890 891


register_operation(PasswordResetOperation)