operations.py 14.2 KB
Newer Older
1
from __future__ import absolute_import, unicode_literals
Dudás Ádám committed
2 3
from logging import getLogger

4
from django.core.exceptions import PermissionDenied
Dudás Ádám committed
5 6 7 8
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from celery.exceptions import TimeLimitExceeded
9

10
from common.operations import Operation, register_operation
11 12
from .tasks.local_tasks import async_instance_operation, async_node_operation
from .models import (
13 14
    Instance, InstanceActivity, InstanceTemplate, Interface, Node,
    NodeActivity,
15
)
Dudás Ádám committed
16 17 18


logger = getLogger(__name__)
19 20


21
class InstanceOperation(Operation):
22
    acl_level = 'owner'
23
    async_operation = async_instance_operation
Dudás Ádám committed
24

25
    def __init__(self, instance):
26
        super(InstanceOperation, self).__init__(subject=instance)
27 28 29
        self.instance = instance

    def check_precond(self):
30 31
        if self.instance.destroyed_at:
            raise self.instance.InstanceDestroyedError(self.instance)
32 33

    def check_auth(self, user):
34 35 36 37
        if not self.instance.has_level(user, self.acl_level):
            raise PermissionDenied("%s doesn't have the required ACL level." %
                                   user)

38
        super(InstanceOperation, self).check_auth(user=user)
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    def create_activity(self, parent, user):
        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.")

            return parent.create_sub(code_suffix=self.activity_code_suffix)
        else:
            return InstanceActivity.create(
                code_suffix=self.activity_code_suffix, instance=self.instance,
                user=user)
56

57

58 59
def register_instance_operation(op_cls, op_id=None):
    return register_operation(Instance, op_cls, op_id)
Dudás Ádám committed
60 61


62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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.")

    def _operation(self, activity, user, system, vlan, managed=None):
        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:
            net.deploy()

        return net


register_instance_operation(AddInterfaceOperation)


85
class DeployOperation(InstanceOperation):
Dudás Ádám committed
86 87 88
    activity_code_suffix = 'deploy'
    id = 'deploy'
    name = _("deploy")
89
    description = _("Deploy new virtual machine with network.")
Dudás Ádám committed
90 91 92 93

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

Dudás Ádám committed
94 95 96 97
    def _operation(self, activity, user, system, timeout=15):
        # Allocate VNC port and host node
        self.instance.allocate_vnc_port()
        self.instance.allocate_node()
Dudás Ádám committed
98 99 100

        # Deploy virtual images
        with activity.sub_activity('deploying_disks'):
Dudás Ádám committed
101 102 103 104 105 106 107 108 109 110 111 112 113
            self.instance.deploy_disks()

        # Deploy VM on remote machine
        with activity.sub_activity('deploying_vm') as deploy_act:
            deploy_act.result = self.instance.deploy_vm(timeout=timeout)

        # Establish network connection (vmdriver)
        with activity.sub_activity('deploying_net'):
            self.instance.deploy_net()

        # Resume vm
        with activity.sub_activity('booting'):
            self.instance.resume_vm(timeout=timeout)
Dudás Ádám committed
114

Dudás Ádám committed
115
        self.instance.renew(which='both', base_activity=activity)
Dudás Ádám committed
116 117


118
register_instance_operation(DeployOperation)
Dudás Ádám committed
119 120


121
class DestroyOperation(InstanceOperation):
Dudás Ádám committed
122 123 124
    activity_code_suffix = 'destroy'
    id = 'destroy'
    name = _("destroy")
125
    description = _("Destroy virtual machine and its networks.")
Dudás Ádám committed
126 127 128 129

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

130
    def _operation(self, activity, user, system):
Dudás Ádám committed
131
        if self.instance.node:
Dudás Ádám committed
132 133 134 135 136 137 138
            # Destroy networks
            with activity.sub_activity('destroying_net'):
                self.instance.destroy_net()

            # Delete virtual machine
            with activity.sub_activity('destroying_vm'):
                self.instance.delete_vm()
Dudás Ádám committed
139 140 141

        # Destroy disks
        with activity.sub_activity('destroying_disks'):
Dudás Ádám committed
142
            self.instance.destroy_disks()
Dudás Ádám committed
143

Dudás Ádám committed
144 145 146 147 148 149 150 151 152
        # 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
153 154 155 156 157

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


158
register_instance_operation(DestroyOperation)
Dudás Ádám committed
159 160


161
class MigrateOperation(InstanceOperation):
Dudás Ádám committed
162 163 164
    activity_code_suffix = 'migrate'
    id = 'migrate'
    name = _("migrate")
165
    description = _("Live migrate running VM to another node.")
Dudás Ádám committed
166

167
    def _operation(self, activity, user, system, to_node=None, timeout=120):
Dudás Ádám committed
168 169 170 171 172
        if not to_node:
            with activity.sub_activity('scheduling') as sa:
                to_node = self.instance.select_node()
                sa.result = to_node

Dudás Ádám committed
173 174 175
        # Shutdown networks
        with activity.sub_activity('shutdown_net'):
            self.instance.shutdown_net()
Dudás Ádám committed
176 177

        with activity.sub_activity('migrate_vm'):
Dudás Ádám committed
178 179
            self.instance.migrate_vm(to_node=to_node, timeout=timeout)

Dudás Ádám committed
180 181 182 183 184
        # Refresh node information
        self.instance.node = to_node
        self.instance.save()
        # Estabilish network connection (vmdriver)
        with activity.sub_activity('deploying_net'):
Dudás Ádám committed
185
            self.instance.deploy_net()
Dudás Ádám committed
186 187


188
register_instance_operation(MigrateOperation)
Dudás Ádám committed
189 190


191
class RebootOperation(InstanceOperation):
Dudás Ádám committed
192 193 194
    activity_code_suffix = 'reboot'
    id = 'reboot'
    name = _("reboot")
195
    description = _("Reboot virtual machine with Ctrl+Alt+Del signal.")
Dudás Ádám committed
196

197
    def _operation(self, activity, user, system, timeout=5):
Dudás Ádám committed
198
        self.instance.reboot_vm(timeout=timeout)
Dudás Ádám committed
199 200


201
register_instance_operation(RebootOperation)
Dudás Ádám committed
202 203


204
class ResetOperation(InstanceOperation):
Dudás Ádám committed
205 206 207
    activity_code_suffix = 'reset'
    id = 'reset'
    name = _("reset")
208
    description = _("Reset virtual machine (reset button).")
Dudás Ádám committed
209

210
    def _operation(self, activity, user, system, timeout=5):
Dudás Ádám committed
211
        self.instance.reset_vm(timeout=timeout)
Dudás Ádám committed
212

213
register_instance_operation(ResetOperation)
Dudás Ádám committed
214 215


216
class SaveAsTemplateOperation(InstanceOperation):
Dudás Ádám committed
217 218 219 220 221 222 223 224 225
    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.
        """)

226 227 228
    def _operation(self, activity, name, user, system, timeout=300,
                   with_shutdown=True, **kwargs):
        if with_shutdown:
229 230 231 232 233 234
            try:
                ShutdownOperation(self.instance).call(parent_activity=activity,
                                                      user=user)
            except Instance.WrongStateError:
                pass

Dudás Ádám committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
        # 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,
            'name': name,
            '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)

254 255
        from storage.models import Disk

Dudás Ádám committed
256 257
        def __try_save_disk(disk):
            try:
Dudás Ádám committed
258
                return disk.save_as()
Dudás Ádám committed
259 260 261
            except Disk.WrongDiskTypeError:
                return disk

262 263 264 265
        with activity.sub_activity('saving_disks'):
            disks = [__try_save_disk(disk)
                     for disk in self.instance.disks.all()]

Dudás Ádám committed
266 267 268 269 270
        # create template and do additional setup
        tmpl = InstanceTemplate(**params)
        tmpl.full_clean()  # Avoiding database errors.
        tmpl.save()
        try:
271
            tmpl.disks.add(*disks)
Dudás Ádám committed
272 273 274 275 276 277 278 279 280 281
            # create interface templates
            for i in self.instance.interface_set.all():
                i.save_as_template(tmpl)
        except:
            tmpl.delete()
            raise
        else:
            return tmpl


282
register_instance_operation(SaveAsTemplateOperation)
Dudás Ádám committed
283 284


285
class ShutdownOperation(InstanceOperation):
Dudás Ádám committed
286 287 288
    activity_code_suffix = 'shutdown'
    id = 'shutdown'
    name = _("shutdown")
289
    description = _("Shutdown virtual machine with ACPI signal.")
Dudás Ádám committed
290

291 292 293 294 295
    def check_precond(self):
        super(ShutdownOperation, self).check_precond()
        if self.instance.status not in ['RUNNING']:
            raise self.instance.WrongStateError(self.instance)

Dudás Ádám committed
296 297 298 299 300 301 302 303 304
    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 = 'STOPPED'

305
    def _operation(self, activity, user, system, timeout=120):
Dudás Ádám committed
306 307 308
        self.instance.shutdown_vm(timeout=timeout)
        self.instance.yield_node()
        self.instance.yield_vnc_port()
Dudás Ádám committed
309 310


311
register_instance_operation(ShutdownOperation)
Dudás Ádám committed
312 313


314
class ShutOffOperation(InstanceOperation):
Dudás Ádám committed
315 316 317
    activity_code_suffix = 'shut_off'
    id = 'shut_off'
    name = _("shut off")
318
    description = _("Shut off VM (plug-out).")
Dudás Ádám committed
319

320
    def on_commit(self, activity):
Dudás Ádám committed
321 322
        activity.resultant_state = 'STOPPED'

323
    def _operation(self, activity, user, system):
Dudás Ádám committed
324 325 326
        # Shutdown networks
        with activity.sub_activity('shutdown_net'):
            self.instance.shutdown_net()
Dudás Ádám committed
327

Dudás Ádám committed
328 329 330 331 332 333 334
        # 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
335 336


337
register_instance_operation(ShutOffOperation)
Dudás Ádám committed
338 339


340
class SleepOperation(InstanceOperation):
Dudás Ádám committed
341 342 343
    activity_code_suffix = 'sleep'
    id = 'sleep'
    name = _("sleep")
344
    description = _("Suspend virtual machine with memory dump.")
Dudás Ádám committed
345 346

    def check_precond(self):
347
        super(SleepOperation, self).check_precond()
Dudás Ádám committed
348 349 350 351 352 353 354 355 356 357 358 359
        if self.instance.status not in ['RUNNING']:
            raise self.instance.WrongStateError(self.instance)

    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'

360
    def _operation(self, activity, user, system, timeout=60):
Dudás Ádám committed
361
        # Destroy networks
Dudás Ádám committed
362 363
        with activity.sub_activity('shutdown_net'):
            self.instance.shutdown_net()
Dudás Ádám committed
364 365 366

        # Suspend vm
        with activity.sub_activity('suspending'):
Dudás Ádám committed
367 368 369 370
            self.instance.suspend_vm(timeout=timeout)

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


373
register_instance_operation(SleepOperation)
Dudás Ádám committed
374 375


376
class WakeUpOperation(InstanceOperation):
Dudás Ádám committed
377 378 379 380 381 382 383 384 385
    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.
        """)

    def check_precond(self):
386
        super(WakeUpOperation, self).check_precond()
Dudás Ádám committed
387 388 389 390 391 392 393 394 395
        if self.instance.status not in ['SUSPENDED']:
            raise self.instance.WrongStateError(self.instance)

    def on_abort(self, activity, error):
        activity.resultant_state = 'ERROR'

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

396
    def _operation(self, activity, user, system, timeout=60):
Dudás Ádám committed
397
        # Schedule vm
Dudás Ádám committed
398 399
        self.instance.allocate_vnc_port()
        self.instance.allocate_node()
Dudás Ádám committed
400 401 402

        # Resume vm
        with activity.sub_activity('resuming'):
Dudás Ádám committed
403
            self.instance.wake_up_vm(timeout=timeout)
Dudás Ádám committed
404 405 406

        # Estabilish network connection (vmdriver)
        with activity.sub_activity('deploying_net'):
Dudás Ádám committed
407
            self.instance.deploy_net()
Dudás Ádám committed
408 409 410 411 412

        # Renew vm
        self.instance.renew(which='both', base_activity=activity)


413
register_instance_operation(WakeUpOperation)
414 415 416 417 418 419 420 421 422


class NodeOperation(Operation):
    async_operation = async_node_operation

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

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    def create_activity(self, parent, user):
        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.")

            return parent.create_sub(code_suffix=self.activity_code_suffix)
        else:
            return NodeActivity.create(code_suffix=self.activity_code_suffix,
                                       node=self.node, user=user)
438 439 440 441 442 443 444 445 446 447


def register_node_operation(op_cls, op_id=None):
    return register_operation(Node, op_cls, op_id)


class FlushOperation(NodeOperation):
    activity_code_suffix = 'flush'
    id = 'flush'
    name = _("flush")
448
    description = _("Disable node and move all instances to other ones.")
449 450 451 452 453 454 455 456 457

    def _operation(self, activity, user, system):
        self.node.disable(user, activity)
        for i in self.node.instance_set.all():
            with activity.sub_activity('migrate_instance_%d' % i.pk):
                i.migrate()


register_node_operation(FlushOperation)