models.py 12.9 KB
Newer Older
1 2
# coding=utf-8

3
from contextlib import contextmanager
4
import logging
5 6
import uuid

7
from django.db.models import (Model, BooleanField, CharField, DateTimeField,
8
                              ForeignKey)
9
from django.utils import timezone
10
from django.utils.translation import ugettext_lazy as _
11
from model_utils.models import TimeStampedModel
12
from sizefield.models import FileSizeField
13

14
from acl.models import AclBase
15
from .tasks import local_tasks, remote_tasks
16
from celery.exceptions import TimeoutError
17
from common.models import ActivityModel, activitycontextimpl, WorkerNotFound
18 19 20 21

logger = logging.getLogger(__name__)


22
class DataStore(Model):
Guba Sándor committed
23

24 25
    """Collection of virtual disks.
    """
26 27 28 29
    name = CharField(max_length=100, unique=True, verbose_name=_('name'))
    path = CharField(max_length=200, unique=True, verbose_name=_('path'))
    hostname = CharField(max_length=40, unique=True,
                         verbose_name=_('hostname'))
Guba Sándor committed
30

31 32 33 34 35 36 37 38
    class Meta:
        ordering = ['name']
        verbose_name = _('datastore')
        verbose_name_plural = _('datastores')

    def __unicode__(self):
        return u'%s (%s)' % (self.name, self.path)

39
    def get_remote_queue_name(self, queue_id):
40 41 42 43 44 45
        logger.debug("Checking for storage queue %s.%s",
                     self.hostname, queue_id)
        if local_tasks.check_queue(self.hostname, queue_id):
            return self.hostname + '.' + queue_id
        else:
            raise WorkerNotFound()
46

47

48
class Disk(AclBase, TimeStampedModel):
Guba Sándor committed
49

50 51
    """A virtual disk.
    """
52 53 54 55 56
    ACL_LEVELS = (
        ('user', _('user')),          # see all details
        ('operator', _('operator')),
        ('owner', _('owner')),        # superuser, can delete, delegate perms
    )
57 58
    TYPES = [('qcow2-norm', 'qcow2 normal'), ('qcow2-snap', 'qcow2 snapshot'),
             ('iso', 'iso'), ('raw-ro', 'raw read-only'), ('raw-rw', 'raw')]
59 60 61 62 63
    name = CharField(blank=True, max_length=100, verbose_name=_("name"))
    filename = CharField(max_length=256, verbose_name=_("filename"))
    datastore = ForeignKey(DataStore, verbose_name=_("datastore"),
                           help_text=_("The datastore that holds the disk."))
    type = CharField(max_length=10, choices=TYPES)
64
    size = FileSizeField()
65 66
    base = ForeignKey('self', blank=True, null=True,
                      related_name='derivatives')
67 68
    ready = BooleanField(default=False,
                         help_text=_("The associated resource is ready."))
69
    dev_num = CharField(default='a', max_length=1,
70
                        verbose_name=_("device number"))
71
    destroyed = DateTimeField(blank=True, default=None, null=True)
72 73 74 75 76 77

    class Meta:
        ordering = ['name']
        verbose_name = _('disk')
        verbose_name_plural = _('disks')

78 79
    class WrongDiskTypeError(Exception):

80 81 82 83 84 85 86 87
        def __init__(self, type, message=None):
            if message is None:
                message = ("Operation can't be invoked on a disk of type '%s'."
                           % type)

            Exception.__init__(self, message)

            self.type = type
88

89 90
    class DiskInUseError(Exception):

91 92 93 94
        def __init__(self, disk, message=None):
            if message is None:
                message = ("The requested operation can't be performed on "
                           "disk '%s (%s)' because it is in use." %
Dudás Ádám committed
95
                           (disk.name, disk.filename))
96 97 98 99

            Exception.__init__(self, message)

            self.disk = disk
100

101 102 103 104 105 106 107 108 109
    @property
    def path(self):
        return self.datastore.path + '/' + self.filename

    @property
    def format(self):
        return {
            'qcow2-norm': 'qcow2',
            'qcow2-snap': 'qcow2',
110
            'iso': 'raw',
111 112 113 114
            'raw-ro': 'raw',
            'raw-rw': 'raw',
        }[self.type]

115 116 117
    @property
    def device_type(self):
        return {
118 119
            'qcow2-norm': 'vd',
            'qcow2-snap': 'vd',
120
            'iso': 'hd',
121 122 123
            'raw-ro': 'vd',
            'raw-rw': 'vd',
        }[self.type]
124

125
    def is_in_use(self):
126
        return any([i.state != 'STOPPED' for i in self.instance_set.all()])
127

128 129
    def get_exclusive(self):
        """Get an instance of the disk for exclusive usage.
130

131 132 133
        This method manipulates the database only.
        """
        type_mapping = {
134 135 136
            'qcow2-norm': 'qcow2-snap',
            'iso': 'iso',
            'raw-ro': 'raw-rw',
137 138 139 140 141 142 143
        }

        if self.type not in type_mapping.keys():
            raise self.WrongDiskTypeError(self.type)

        filename = self.filename if self.type == 'iso' else str(uuid.uuid4())
        new_type = type_mapping[self.type]
144

145 146 147
        return Disk.objects.create(base=self, datastore=self.datastore,
                                   filename=filename, name=self.name,
                                   size=self.size, type=new_type)
148 149 150

    def get_vmdisk_desc(self):
        return {
151
            'source': self.path,
152
            'driver_type': self.format,
153
            'driver_cache': 'none',
154
            'target_device': self.device_type + self.dev_num,
155
            'disk_device': 'cdrom' if self.type == 'iso' else 'disk'
156 157
        }

158 159 160 161 162 163 164 165 166 167
    def get_disk_desc(self):
        return {
            'name': self.filename,
            'dir': self.datastore.path,
            'format': self.format,
            'size': self.size,
            'base_name': self.base.filename if self.base else None,
            'type': 'snapshot' if self.type == 'qcow2-snap' else 'normal'
        }

168 169 170 171 172 173
    def get_remote_queue_name(self, queue_id):
        if self.datastore:
            return self.datastore.get_remote_queue_name(queue_id)
        else:
            return None

174 175 176
    def __unicode__(self):
        return u"%s (#%d)" % (self.name, self.id)

177 178 179 180 181
    def clean(self, *args, **kwargs):
        if self.size == "" and self.base:
            self.size = self.base.size
        super(Disk, self).clean(*args, **kwargs)

182
    def deploy(self, user=None, task_uuid=None, timeout=15):
183 184 185 186 187
        """Reify the disk model on the associated data store.

        :param self: the disk model to reify
        :type self: storage.models.Disk

188 189 190 191 192 193 194
        :param user: The user who's issuing the command.
        :type user: django.contrib.auth.models.User

        :param task_uuid: The task's UUID, if the command is being executed
                          asynchronously.
        :type task_uuid: str

195 196 197 198
        :return: True if a new reification of the disk has been created;
                 otherwise, False.
        :rtype: bool
        """
199 200 201 202
        if self.destroyed:
            self.destroyed = None
            self.save()

203
        if self.ready:
204
            return False
205

206 207 208 209
        with disk_activity(code_suffix='deploy', disk=self,
                           task_uuid=task_uuid, user=user) as act:

            # Delegate create / snapshot jobs
210
            queue_name = self.get_remote_queue_name('storage')
211 212 213 214
            disk_desc = self.get_disk_desc()
            if self.type == 'qcow2-snap':
                with act.sub_activity('creating_snapshot'):
                    remote_tasks.snapshot.apply_async(args=[disk_desc],
215 216
                                                      queue=queue_name
                                                      ).get(timeout=timeout)
217 218 219
            else:
                with act.sub_activity('creating_disk'):
                    remote_tasks.create.apply_async(args=[disk_desc],
220 221
                                                    queue=queue_name
                                                    ).get(timeout=timeout)
222 223 224

            self.ready = True
            self.save()
225

226
            return True
227

228
    def deploy_async(self, user=None):
229 230
        """Execute deploy asynchronously.
        """
231 232
        return local_tasks.deploy.apply_async(args=[self, user],
                                              queue="localhost.man")
233

234 235 236 237 238 239 240 241
    @classmethod
    def create_empty(cls, params={}, user=None):
        disk = cls()
        disk.__dict__.update(params)
        disk.save()
        return disk

    @classmethod
242 243 244 245
    def create_from_url_async(cls, url, params=None, user=None):
        return local_tasks.create_from_url.apply_async(kwargs={
            'cls': cls, 'url': url, 'params': params, 'user': user},
            queue='localhost.man')
246

247 248
    def create_from_url(cls, url, params={}, user=None, task_uuid=None,
                        abortable_task=None):
249 250 251 252 253
        disk = cls()
        disk.filename = str(uuid.uuid4())
        disk.type = "iso"
        disk.size = 1
        disk.datastore = DataStore.objects.all()[0]
254 255
        if params:
            disk.__dict__.update(params)
256 257 258
        disk.save()
        queue_name = disk.get_remote_queue_name('storage')

259 260 261 262 263 264 265 266 267
        def __on_abort(activity, error):
            activity.disk.destroyed = timezone.now()
            activity.disk.save()

        if abortable_task:
            from celery.contrib.abortable import AbortableAsyncResult

            class AbortException(Exception):
                pass
268 269

        with disk_activity(code_suffix='download', disk=disk,
270 271 272 273 274 275 276 277 278 279 280 281 282 283
                           task_uuid=task_uuid, user=user,
                           on_abort=__on_abort):
            result = remote_tasks.download.apply_async(
                kwargs={'url': url, 'parent_id': task_uuid,
                        'disk': disk.get_disk_desc()},
                queue=queue_name)
            while True:
                try:
                    size = result.get(timeout=5)
                    break
                except TimeoutError:
                    if abortable_task and abortable_task.is_aborted():
                        AbortableAsyncResult(result.id).abort()
                        raise AbortException("Download aborted by user.")
284
            disk.size = size
285
            disk.ready = True
286 287
            disk.save()

288
    def destroy(self, user=None, task_uuid=None):
289 290 291
        if self.destroyed:
            return False

292 293 294 295
        with disk_activity(code_suffix='destroy', disk=self,
                           task_uuid=task_uuid, user=user):
            self.destroyed = timezone.now()
            self.save()
296

297
            return True
298

299
    def destroy_async(self, user=None):
300 301
        """Execute destroy asynchronously.
        """
302 303
        return local_tasks.destroy.apply_async(args=[self, user],
                                               queue='localhost.man')
304

305
    def restore(self, user=None, task_uuid=None):
306
        """Restore destroyed disk.
307 308 309 310 311 312 313 314
        """
        # TODO
        pass

    def restore_async(self, user=None):
        local_tasks.restore.apply_async(args=[self, user],
                                        queue='localhost.man')

315
    def save_as(self, user=None, task_uuid=None, timeout=120):
316 317 318 319 320 321 322 323 324 325 326 327
        mapping = {
            'qcow2-snap': ('qcow2-norm', self.base),
        }
        if self.type not in mapping.keys():
            raise self.WrongDiskTypeError(self.type)

        if self.is_in_use():
            raise self.DiskInUseError(self)

        # from this point on, the caller has to guarantee that the disk is not
        # going to be used until the operation is complete

328
        with disk_activity(code_suffix='save_as', disk=self,
329
                           task_uuid=task_uuid, user=user, timeout=300):
330 331 332 333 334

            filename = str(uuid.uuid4())
            new_type, new_base = mapping[self.type]

            disk = Disk.objects.create(base=new_base, datastore=self.datastore,
335
                                       filename=filename, name=self.name,
336 337
                                       size=self.size, type=new_type)

338
            queue_name = self.get_remote_queue_name('storage')
339 340
            remote_tasks.merge.apply_async(args=[self.get_disk_desc(),
                                                 disk.get_disk_desc()],
341 342
                                           queue=queue_name
                                           ).get(timeout=timeout)
343 344 345 346 347 348 349 350 351 352 353 354 355

            disk.ready = True
            disk.save()

            return disk


class DiskActivity(ActivityModel):
    disk = ForeignKey(Disk, related_name='activity_log',
                      help_text=_('Disk this activity works on.'),
                      verbose_name=_('disk'))

    @classmethod
356
    def create(cls, code_suffix, disk, task_uuid=None, user=None):
357
        act = cls(activity_code='storage.Disk.' + code_suffix,
358
                  disk=disk, parent=None, started=timezone.now(),
359
                  task_uuid=task_uuid, user=user)
360
        act.save()
361
        return act
362

363 364 365
    def create_sub(self, code_suffix, task_uuid=None):
        act = DiskActivity(
            activity_code=self.activity_code + '.' + code_suffix,
366
            disk=self.disk, parent=self, started=timezone.now(),
367 368 369
            task_uuid=task_uuid, user=self.user)
        act.save()
        return act
370

371 372 373
    @contextmanager
    def sub_activity(self, code_suffix, task_uuid=None):
        act = self.create_sub(code_suffix, task_uuid)
374
        return activitycontextimpl(act)
375

376

377
@contextmanager
378 379
def disk_activity(code_suffix, disk, task_uuid=None, user=None,
                  on_abort=None, on_commit=None):
380
    act = DiskActivity.create(code_suffix, disk, task_uuid, user)
381
    return activitycontextimpl(act, on_abort=on_abort, on_commit=on_commit)