models.py 34.9 KB
Newer Older
1
# Copyright 2011-2012 GRNET S.A. All rights reserved.
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
27
28
29
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#   1. Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of GRNET S.A.

30
31
import datetime

32
from copy import deepcopy
33
from django.conf import settings
34
from django.db import models
35
36

import utils
37
from contextlib import contextmanager
38
from hashlib import sha1
39
from snf_django.lib.api import faults
40
from django.conf import settings as snf_settings
41
from aes_encrypt import encrypt_db_charfield, decrypt_db_charfield
42

43
from synnefo.db import pools, fields
44

45
46
from synnefo.logic.rapi_pool import (get_rapi_client,
                                     put_rapi_client)
47

48
49
50
import logging
log = logging.getLogger(__name__)

51

52
class Flavor(models.Model):
53
    cpu = models.IntegerField('Number of CPUs', default=0)
54
55
    ram = models.IntegerField('RAM size in MiB', default=0)
    disk = models.IntegerField('Disk size in GiB', default=0)
56
    disk_template = models.CharField('Disk template', max_length=32)
57
    deleted = models.BooleanField('Deleted', default=False)
58

Vassilios Karakoidas's avatar
Vassilios Karakoidas committed
59
    class Meta:
60
        verbose_name = u'Virtual machine flavor'
61
        unique_together = ('cpu', 'ram', 'disk', 'disk_template')
62

63
64
    @property
    def name(self):
65
        """Returns flavor name (generated)"""
66
67
        return u'C%dR%dD%d%s' % (self.cpu, self.ram, self.disk,
                                 self.disk_template)
68

69
    def __unicode__(self):
70
        return "<%s:%s>" % (str(self.id), self.name)
71

72

73
74
75
76
77
class Backend(models.Model):
    clustername = models.CharField('Cluster Name', max_length=128, unique=True)
    port = models.PositiveIntegerField('Port', default=5080)
    username = models.CharField('Username', max_length=64, blank=True,
                                null=True)
78
    password_hash = models.CharField('Password', max_length=128, blank=True,
Christos Stavrakakis's avatar
Christos Stavrakakis committed
79
                                     null=True)
80
81
    # Sha1 is up to 40 characters long
    hash = models.CharField('Hash', max_length=40, editable=False, null=False)
82
83
84
85
    # Unique index of the Backend, used for the mac-prefixes of the
    # BackendNetworks
    index = models.PositiveIntegerField('Index', null=False, unique=True,
                                        default=0)
86
87
    drained = models.BooleanField('Drained', default=False, null=False)
    offline = models.BooleanField('Offline', default=False, null=False)
88
89
90
    # Type of hypervisor
    hypervisor = models.CharField('Hypervisor', max_length=32, default="kvm",
                                  null=False)
91
    disk_templates = fields.SeparatedValuesField("Disk Templates", null=True)
92
93
94
95
96
97
98
99
100
101
102
103
    # Last refresh of backend resources
    updated = models.DateTimeField(auto_now_add=True)
    # Backend resources
    mfree = models.PositiveIntegerField('Free Memory', default=0, null=False)
    mtotal = models.PositiveIntegerField('Total Memory', default=0, null=False)
    dfree = models.PositiveIntegerField('Free Disk', default=0, null=False)
    dtotal = models.PositiveIntegerField('Total Disk', default=0, null=False)
    pinst_cnt = models.PositiveIntegerField('Primary Instances', default=0,
                                            null=False)
    ctotal = models.PositiveIntegerField('Total number of logical processors',
                                         default=0, null=False)

104
105
106
107
108
109
    HYPERVISORS = (
        ("kvm", "Linux KVM hypervisor"),
        ("xen-pvm", "Xen PVM hypervisor"),
        ("xen-hvm", "Xen KVM hypervisor"),
    )

110
111
112
113
114
    class Meta:
        verbose_name = u'Backend'
        ordering = ["clustername"]

    def __unicode__(self):
Christos Stavrakakis's avatar
Christos Stavrakakis committed
115
        return self.clustername + "(id=" + str(self.id) + ")"
116
117
118
119
120

    @property
    def backend_id(self):
        return self.id

121
    def get_client(self):
122
        """Get or create a client. """
123
        if self.offline:
124
125
            raise faults.ServiceUnavailable("Backend '%s' is offline" %
                                            self)
126
        return get_rapi_client(self.id, self.hash,
127
128
                               self.clustername,
                               self.port,
129
130
131
132
133
134
                               self.username,
                               self.password)

    @staticmethod
    def put_client(client):
            put_rapi_client(client)
135
136
137

    def create_hash(self):
        """Create a hash for this backend. """
Christos Stavrakakis's avatar
Christos Stavrakakis committed
138
139
140
        sha = sha1('%s%s%s%s' %
                   (self.clustername, self.port, self.username, self.password))
        return sha.hexdigest()
141

142
143
144
145
146
147
148
149
    @property
    def password(self):
        return decrypt_db_charfield(self.password_hash)

    @password.setter
    def password(self, value):
        self.password_hash = encrypt_db_charfield(value)

150
151
152
153
154
155
156
    def save(self, *args, **kwargs):
        # Create a new hash each time a Backend is saved
        old_hash = self.hash
        self.hash = self.create_hash()
        super(Backend, self).save(*args, **kwargs)
        if self.hash != old_hash:
            # Populate the new hash to the new instances
Christos Stavrakakis's avatar
Christos Stavrakakis committed
157
158
            self.virtual_machines.filter(deleted=False)\
                                 .update(backend_hash=self.hash)
159

160
161
162
163
164
    def __init__(self, *args, **kwargs):
        super(Backend, self).__init__(*args, **kwargs)
        if not self.pk:
            # Generate a unique index for the Backend
            indexes = Backend.objects.all().values_list('index', flat=True)
165
166
167
168
169
            try:
                first_free = [x for x in xrange(0, 16) if x not in indexes][0]
                self.index = first_free
            except IndexError:
                raise Exception("Can not create more than 16 backends")
170

171
172
173
174
175
176
177
178
179
    def use_hotplug(self):
        return self.hypervisor == "kvm" and snf_settings.GANETI_USE_HOTPLUG

    def get_create_params(self):
        params = deepcopy(snf_settings.GANETI_CREATEINSTANCE_KWARGS)
        params["hvparams"] = params.get("hvparams", {})\
                                   .get(self.hypervisor, {})
        return params

180

181
182
183
184
185
186
187
188
189
190
191
192
# A backend job may be in one of the following possible states
BACKEND_STATUSES = (
    ('queued', 'request queued'),
    ('waiting', 'request waiting for locks'),
    ('canceling', 'request being canceled'),
    ('running', 'request running'),
    ('canceled', 'request canceled'),
    ('success', 'request completed successfully'),
    ('error', 'request returned error')
)


193
class QuotaHolderSerial(models.Model):
194
195
196
197
198
199
200
201
202
203
    """Model representing a serial for a Quotaholder Commission.

    serial:   The serial that Quotaholder assigned to this commission
    pending:  Whether it has been decided to accept or reject this commission
    accept:   If pending is False, this attribute indicates whether to accept
              or reject this commission
    resolved: Whether this commission has been accepted or rejected to
              Quotaholder.

    """
Christos Stavrakakis's avatar
Christos Stavrakakis committed
204
205
    serial = models.BigIntegerField(null=False, primary_key=True,
                                    db_index=True)
206
    pending = models.BooleanField(default=True, db_index=True)
207
208
    accept = models.BooleanField(default=False)
    resolved = models.BooleanField(default=False)
209
210
211
212
213

    class Meta:
        verbose_name = u'Quota Serial'
        ordering = ["serial"]

214
215
216
    def __unicode__(self):
        return u"<serial: %s>" % self.serial

217

Vassilios Karakoidas's avatar
Vassilios Karakoidas committed
218
class VirtualMachine(models.Model):
219
    # The list of possible actions for a VM
220
    ACTIONS = (
Christos Stavrakakis's avatar
Christos Stavrakakis committed
221
222
223
224
225
        ('CREATE', 'Create VM'),
        ('START', 'Start VM'),
        ('STOP', 'Shutdown VM'),
        ('SUSPEND', 'Admin Suspend VM'),
        ('REBOOT', 'Reboot VM'),
226
227
        ('DESTROY', 'Destroy VM'),
        ('RESIZE', 'Resize a VM'),
228
229
        ('ADDFLOATINGIP', 'Add floating IP to VM'),
        ('REMOVEFLOATINGIP', 'Add floating IP to VM'),
230
    )
231

232
    # The internal operating state of a VM
233
234
235
236
237
    OPER_STATES = (
        ('BUILD', 'Queued for creation'),
        ('ERROR', 'Creation failed'),
        ('STOPPED', 'Stopped'),
        ('STARTED', 'Started'),
238
239
        ('DESTROYED', 'Destroyed'),
        ('RESIZE', 'Resizing')
240
    )
241

242
    # The list of possible operations on the backend
243
244
245
246
247
    BACKEND_OPCODES = (
        ('OP_INSTANCE_CREATE', 'Create Instance'),
        ('OP_INSTANCE_REMOVE', 'Remove Instance'),
        ('OP_INSTANCE_STARTUP', 'Startup Instance'),
        ('OP_INSTANCE_SHUTDOWN', 'Shutdown Instance'),
248
249
250
251
252
253
        ('OP_INSTANCE_REBOOT', 'Reboot Instance'),

        # These are listed here for completeness,
        # and are ignored for the time being
        ('OP_INSTANCE_SET_PARAMS', 'Set Instance Parameters'),
        ('OP_INSTANCE_QUERY_DATA', 'Query Instance Data'),
254
255
256
257
258
259
        ('OP_INSTANCE_REINSTALL', 'Reinstall Instance'),
        ('OP_INSTANCE_ACTIVATE_DISKS', 'Activate Disks'),
        ('OP_INSTANCE_DEACTIVATE_DISKS', 'Deactivate Disks'),
        ('OP_INSTANCE_REPLACE_DISKS', 'Replace Disks'),
        ('OP_INSTANCE_MIGRATE', 'Migrate Instance'),
        ('OP_INSTANCE_CONSOLE', 'Get Instance Console'),
260
261
        ('OP_INSTANCE_RECREATE_DISKS', 'Recreate Disks'),
        ('OP_INSTANCE_FAILOVER', 'Failover Instance')
262
    )
263

264
265
    # The operating state of a VM,
    # upon the successful completion of a backend operation.
266
267
    # IMPORTANT: Make sure all keys have a corresponding
    # entry in BACKEND_OPCODES if you update this field, see #1035, #1111.
268
269
270
271
272
    OPER_STATE_FROM_OPCODE = {
        'OP_INSTANCE_CREATE': 'STARTED',
        'OP_INSTANCE_REMOVE': 'DESTROYED',
        'OP_INSTANCE_STARTUP': 'STARTED',
        'OP_INSTANCE_SHUTDOWN': 'STOPPED',
273
274
        'OP_INSTANCE_REBOOT': 'STARTED',
        'OP_INSTANCE_SET_PARAMS': None,
275
        'OP_INSTANCE_QUERY_DATA': None,
276
277
        'OP_INSTANCE_REINSTALL': None,
        'OP_INSTANCE_ACTIVATE_DISKS': None,
278
        'OP_INSTANCE_DEACTIVATE_DISKS': None,
279
        'OP_INSTANCE_REPLACE_DISKS': None,
280
281
        'OP_INSTANCE_MIGRATE': None,
        'OP_INSTANCE_CONSOLE': None,
282
283
        'OP_INSTANCE_RECREATE_DISKS': None,
        'OP_INSTANCE_FAILOVER': None
284
285
    }

286
287
288
    # This dictionary contains the correspondence between
    # internal operating states and Server States as defined
    # by the Rackspace API.
289
290
291
292
293
    RSAPI_STATE_FROM_OPER_STATE = {
        "BUILD": "BUILD",
        "ERROR": "ERROR",
        "STOPPED": "STOPPED",
        "STARTED": "ACTIVE",
294
295
        'RESIZE': 'RESIZE',
        'DESTROYED': 'DELETED',
296
297
    }

298
    name = models.CharField('Virtual Machine Name', max_length=255)
299
    userid = models.CharField('User ID of the owner', max_length=100,
300
                              db_index=True, null=False)
301
    backend = models.ForeignKey(Backend, null=True,
302
303
                                related_name="virtual_machines",
                                on_delete=models.PROTECT)
304
    backend_hash = models.CharField(max_length=128, null=True, editable=False)
305
306
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
307
    imageid = models.CharField(max_length=100, null=False)
308
    hostid = models.CharField(max_length=100)
309
    flavor = models.ForeignKey(Flavor, on_delete=models.PROTECT)
310
    deleted = models.BooleanField('Deleted', default=False, db_index=True)
311
    suspended = models.BooleanField('Administratively Suspended',
312
                                    default=False)
313
    serial = models.ForeignKey(QuotaHolderSerial,
314
315
                               related_name='virtual_machine', null=True,
                               on_delete=models.SET_NULL)
316

317
    # VM State
318
319
320
321
    # The following fields are volatile data, in the sense
    # that they need not be persistent in the DB, but rather
    # get generated at runtime by quering Ganeti and applying
    # updates received from Ganeti.
322

323
324
325
    # In the future they could be moved to a separate caching layer
    # and removed from the database.
    # [vkoukis] after discussion with [faidon].
326
327
328
329
    action = models.CharField(choices=ACTIONS, max_length=30, null=True,
                              default=None)
    operstate = models.CharField(choices=OPER_STATES, max_length=30,
                                 null=False, default="BUILD")
330
    backendjobid = models.PositiveIntegerField(null=True)
331
    backendopcode = models.CharField(choices=BACKEND_OPCODES, max_length=30,
332
                                     null=True)
333
    backendjobstatus = models.CharField(choices=BACKEND_STATUSES,
334
                                        max_length=30, null=True)
335
    backendlogmsg = models.TextField(null=True)
336
    buildpercentage = models.IntegerField(default=0)
337
    backendtime = models.DateTimeField(default=datetime.datetime.min)
338

339
340
341
    # Latest action and corresponding Ganeti job ID, for actions issued
    # by the API
    task = models.CharField(max_length=64, null=True)
342
    task_job_id = models.BigIntegerField(null=True)
343

344
345
    def get_client(self):
        if self.backend:
346
            return self.backend.get_client()
347
        else:
348
            raise faults.ServiceUnavailable("VirtualMachine without backend")
349

350
351
352
353
354
355
    def get_last_diagnostic(self, **filters):
        try:
            return self.diagnostics.filter()[0]
        except IndexError:
            return None

356
357
358
359
    @staticmethod
    def put_client(client):
            put_rapi_client(client)

360
361
362
363
364
365
    def save(self, *args, **kwargs):
        # Store hash for first time saved vm
        if (self.id is None or self.backend_hash == '') and self.backend:
            self.backend_hash = self.backend.hash
        super(VirtualMachine, self).save(*args, **kwargs)

366
    @property
367
    def backend_vm_id(self):
368
        """Returns the backend id for this VM by prepending backend-prefix."""
369
370
        if not self.id:
            raise VirtualMachine.InvalidBackendIdError("self.id is None")
371
        return "%s%s" % (settings.BACKEND_PREFIX_ID, str(self.id))
372

373
374
375
    class Meta:
        verbose_name = u'Virtual machine instance'
        get_latest_by = 'created'
376

377
    def __unicode__(self):
378
379
        return u"<vm:%s@backend:%s router:%s>" % (self.id, self.backend_id,
                                                  self.router)
380

Christos Stavrakakis's avatar
Christos Stavrakakis committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
    # Error classes
    class InvalidBackendIdError(Exception):
        def __init__(self, value):
            self.value = value

        def __str__(self):
            return repr(self.value)

    class InvalidBackendMsgError(Exception):
        def __init__(self, opcode, status):
            self.opcode = opcode
            self.status = status

        def __str__(self):
            return repr('<opcode: %s, status: %s>' % (self.opcode,
                        self.status))

    class InvalidActionError(Exception):
        def __init__(self, action):
            self._action = action

        def __str__(self):
            return repr(str(self._action))

405

Vassilios Karakoidas's avatar
Vassilios Karakoidas committed
406
407
408
class VirtualMachineMetadata(models.Model):
    meta_key = models.CharField(max_length=50)
    meta_value = models.CharField(max_length=500)
409
410
    vm = models.ForeignKey(VirtualMachine, related_name='metadata',
                           on_delete=models.CASCADE)
411

Vassilios Karakoidas's avatar
Vassilios Karakoidas committed
412
    class Meta:
413
        unique_together = (('meta_key', 'vm'),)
414
        verbose_name = u'Key-value pair of metadata for a VM.'
415

Vassilios Karakoidas's avatar
Vassilios Karakoidas committed
416
    def __unicode__(self):
417
        return u'%s: %s' % (self.meta_key, self.meta_value)
Vassilios Karakoidas's avatar
Vassilios Karakoidas committed
418
419


420
class Network(models.Model):
421
    OPER_STATES = (
422
        ('PENDING', 'Pending'),  # Unused because of lazy networks
423
        ('ACTIVE', 'Active'),
424
425
426
427
428
        ('DELETED', 'Deleted'),
        ('ERROR', 'Error')
    )

    ACTIONS = (
Christos Stavrakakis's avatar
Christos Stavrakakis committed
429
430
        ('CREATE', 'Create Network'),
        ('DESTROY', 'Destroy Network'),
431
432
        ('ADD', 'Add server to Network'),
        ('REMOVE', 'Remove server from Network'),
433
434
435
436
437
438
439
440
441
    )

    RSAPI_STATE_FROM_OPER_STATE = {
        'PENDING': 'PENDING',
        'ACTIVE': 'ACTIVE',
        'DELETED': 'DELETED',
        'ERROR': 'ERROR'
    }

442
443
    FLAVORS = {
        'CUSTOM': {
Christos Stavrakakis's avatar
Christos Stavrakakis committed
444
445
446
447
448
            'mode': 'bridged',
            'link': settings.DEFAULT_BRIDGE,
            'mac_prefix': settings.DEFAULT_MAC_PREFIX,
            'tags': None,
            'desc': "Basic flavor used for a bridged network",
449
450
        },
        'IP_LESS_ROUTED': {
Christos Stavrakakis's avatar
Christos Stavrakakis committed
451
452
453
454
455
456
            'mode': 'routed',
            'link': settings.DEFAULT_ROUTING_TABLE,
            'mac_prefix': settings.DEFAULT_MAC_PREFIX,
            'tags': 'ip-less-routed',
            'desc': "Flavor used for an IP-less routed network using"
                    " Proxy ARP",
457
458
        },
        'MAC_FILTERED': {
Christos Stavrakakis's avatar
Christos Stavrakakis committed
459
460
461
462
463
464
465
            'mode': 'bridged',
            'link': settings.DEFAULT_MAC_FILTERED_BRIDGE,
            'mac_prefix': 'pool',
            'tags': 'private-filtered',
            'desc': "Flavor used for bridged networks that offer isolation"
                    " via filtering packets based on their src "
                    " MAC (ebtables)",
466
467
        },
        'PHYSICAL_VLAN': {
Christos Stavrakakis's avatar
Christos Stavrakakis committed
468
469
470
471
472
473
            'mode': 'bridged',
            'link': 'pool',
            'mac_prefix': settings.DEFAULT_MAC_PREFIX,
            'tags': 'physical-vlan',
            'desc': "Flavor used for bridged network that offer isolation"
                    " via dedicated physical vlan",
474
475
        },
    }
476

477
478
479
    NETWORK_NAME_LENGTH = 128

    name = models.CharField('Network Name', max_length=NETWORK_NAME_LENGTH)
480
481
    userid = models.CharField('User ID of the owner', max_length=128,
                              null=True, db_index=True)
482
483
484
    flavor = models.CharField('Flavor', max_length=32, null=False)
    mode = models.CharField('Network Mode', max_length=16, null=True)
    link = models.CharField('Network Link', max_length=32, null=True)
485
    mac_prefix = models.CharField('MAC Prefix', max_length=32, null=False)
486
    tags = models.CharField('Network Tags', max_length=128, null=True)
487
    public = models.BooleanField(default=False, db_index=True)
488
489
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
490
    deleted = models.BooleanField('Deleted', default=False, db_index=True)
491
492
    state = models.CharField(choices=OPER_STATES, max_length=32,
                             default='PENDING')
493
    machines = models.ManyToManyField(VirtualMachine,
494
                                      through='NetworkInterface')
495
496
    action = models.CharField(choices=ACTIONS, max_length=32, null=True,
                              default=None)
497
    drained = models.BooleanField("Drained", default=False, null=False)
498
    floating_ip_pool = models.BooleanField('Floating IP Pool', null=False,
Christos Stavrakakis's avatar
Christos Stavrakakis committed
499
                                           default=False)
500
    external_router = models.BooleanField(default=False)
501
    serial = models.ForeignKey(QuotaHolderSerial, related_name='network',
502
                               null=True, on_delete=models.SET_NULL)
Christos Stavrakakis's avatar
Christos Stavrakakis committed
503

504
    def __unicode__(self):
505
        return "<Network: %s>" % str(self.id)
506

507
508
    @property
    def backend_id(self):
509
        """Return the backend id by prepending backend-prefix."""
510
511
        if not self.id:
            raise Network.InvalidBackendIdError("self.id is None")
512
        return "%snet-%s" % (settings.BACKEND_PREFIX_ID, str(self.id))
513
514
515
516
517
518

    @property
    def backend_tag(self):
        """Return the network tag to be used in backend

        """
519
520
521
522
        if self.tags:
            return self.tags.split(',')
        else:
            return []
523

524
525
526
    def create_backend_network(self, backend=None):
        """Create corresponding BackendNetwork entries."""

Christos Stavrakakis's avatar
Christos Stavrakakis committed
527
528
        backends = [backend] if backend else\
            Backend.objects.filter(offline=False)
529
        for backend in backends:
Christos Stavrakakis's avatar
Christos Stavrakakis committed
530
531
532
533
            backend_exists =\
                BackendNetwork.objects.filter(backend=backend, network=self)\
                                      .exists()
            if not backend_exists:
534
                BackendNetwork.objects.create(backend=backend, network=self)
535

536
    def get_pool(self, locked=True):
537
538
539
540
        try:
            subnet = self.subnets.get(ipversion=4, deleted=False)
        except Subnet.DoesNotExist:
            raise pools.EmptyPool
541
542
543
        return subnet.get_pool(locked=locked)

    def allocate_address(self, userid):
544
        try:
545
546
547
548
            subnet = self.subnets.get(ipversion=4, deleted=False)
        except Subnet.DoesNotExist:
            raise pools.EmptyPool
        return subnet.allocate_address(userid)
Christos Stavrakakis's avatar
Christos Stavrakakis committed
549

550
    def reserve_address(self, address, external=False):
Christos Stavrakakis's avatar
Christos Stavrakakis committed
551
        pool = self.get_pool()
552
        pool.reserve(address, external=external)
Christos Stavrakakis's avatar
Christos Stavrakakis committed
553
        pool.save()
Christos Stavrakakis's avatar
Christos Stavrakakis committed
554

555
    def release_address(self, address, external=True):
Christos Stavrakakis's avatar
Christos Stavrakakis committed
556
        pool = self.get_pool()
557
        pool.put(address, external=external)
Christos Stavrakakis's avatar
Christos Stavrakakis committed
558
        pool.save()
Christos Stavrakakis's avatar
Christos Stavrakakis committed
559

560
561
562
563
564
565
566
567
568
569
570
571
572
    @property
    def subnet4(self):
        return self.get_subnet(version=4)

    @property
    def subnet6(self):
        return self.get_subnet(version=6)

    def get_subnet(self, version=4):
        for subnet in self.subnets.all():
            if subnet.ipversion == version:
                return subnet.cidr

573
574
575
576
577
578
579
580
581
582
583
    def ip_count(self):
        """Return the total and free IPv4 addresses of the network."""
        subnets = self.subnets.filter(ipversion=4).prefetch_related("ip_pools")
        total, free = 0, 0
        for subnet in subnets:
            for ip_pool in subnet.ip_pools.all():
                pool = ip_pool.pool
                total += pool.pool_size
                free += pool.count_available()
        return total, free

Christos Stavrakakis's avatar
Christos Stavrakakis committed
584
585
586
587
588
589
590
591
592
593
594
595
596
    class InvalidBackendIdError(Exception):
        def __init__(self, value):
            self.value = value

        def __str__(self):
            return repr(self.value)

    class InvalidBackendMsgError(Exception):
        def __init__(self, opcode, status):
            self.opcode = opcode
            self.status = status

        def __str__(self):
Christos Stavrakakis's avatar
Christos Stavrakakis committed
597
598
            return repr('<opcode: %s, status: %s>'
                        % (self.opcode, self.status))
Christos Stavrakakis's avatar
Christos Stavrakakis committed
599
600
601
602
603
604
605
606

    class InvalidActionError(Exception):
        def __init__(self, action):
            self._action = action

        def __str__(self):
            return repr(str(self._action))

607

608
609
610
611
612
613
614
615
class Subnet(models.Model):
    SUBNET_NAME_LENGTH = 128

    network = models.ForeignKey('Network', null=False, db_index=True,
                                related_name="subnets")
    name = models.CharField('Subnet Name', max_length=SUBNET_NAME_LENGTH,
                            null=True)
    ipversion = models.IntegerField('IP Version', default=4, null=False)
616
    cidr = models.CharField('Subnet', max_length=64, null=False)
617
    gateway = models.CharField('Gateway', max_length=64, null=True)
618
619
620
    dhcp = models.BooleanField('DHCP', default=True, null=False)
    deleted = models.BooleanField('Deleted', default=False, db_index=True,
                                  null=False)
621
622
623
624
    host_routes = fields.SeparatedValuesField('Host Routes', null=True)
    dns_nameservers = fields.SeparatedValuesField('DNS Nameservers', null=True)

    def __unicode__(self):
625
626
        msg = u"<Subnet %s, Network: %s, CIDR: %s>"
        return msg % (self.id, self.network_id, self.cidr)
627

628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
    def get_pool(self, locked=True):
        if self.ipversion == 6:
            raise Exception("IPv6 Subnets have no IP Pool.")
        ip_pools = self.ip_pools
        if locked:
            ip_pools = ip_pools.select_for_update()
        return ip_pools.all()[0].pool

    def allocate_address(self, userid):
        pool = self.get_pool(locked=True)
        address = pool.get()
        pool.save()
        return IPAddress.objects.create(network=self.network, subnet=self,
                                        address=address, userid=userid)

643

644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
class BackendNetwork(models.Model):
    OPER_STATES = (
        ('PENDING', 'Pending'),
        ('ACTIVE', 'Active'),
        ('DELETED', 'Deleted'),
        ('ERROR', 'Error')
    )

    # The list of possible operations on the backend
    BACKEND_OPCODES = (
        ('OP_NETWORK_ADD', 'Create Network'),
        ('OP_NETWORK_CONNECT', 'Activate Network'),
        ('OP_NETWORK_DISCONNECT', 'Deactivate Network'),
        ('OP_NETWORK_REMOVE', 'Remove Network'),
        # These are listed here for completeness,
        # and are ignored for the time being
        ('OP_NETWORK_SET_PARAMS', 'Set Network Parameters'),
        ('OP_NETWORK_QUERY_DATA', 'Query Network Data')
    )

    # The operating state of a Netowork,
    # upon the successful completion of a backend operation.
    # IMPORTANT: Make sure all keys have a corresponding
    # entry in BACKEND_OPCODES if you update this field, see #1035, #1111.
    OPER_STATE_FROM_OPCODE = {
        'OP_NETWORK_ADD': 'PENDING',
        'OP_NETWORK_CONNECT': 'ACTIVE',
        'OP_NETWORK_DISCONNECT': 'PENDING',
        'OP_NETWORK_REMOVE': 'DELETED',
        'OP_NETWORK_SET_PARAMS': None,
        'OP_NETWORK_QUERY_DATA': None
    }

677
678
    network = models.ForeignKey(Network, related_name='backend_networks',
                                on_delete=models.CASCADE)
679
680
    backend = models.ForeignKey(Backend, related_name='networks',
                                on_delete=models.PROTECT)
681
682
683
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    deleted = models.BooleanField('Deleted', default=False)
684
    mac_prefix = models.CharField('MAC Prefix', max_length=32, null=False)
685
686
687
688
689
690
691
692
693
694
695
    operstate = models.CharField(choices=OPER_STATES, max_length=30,
                                 default='PENDING')
    backendjobid = models.PositiveIntegerField(null=True)
    backendopcode = models.CharField(choices=BACKEND_OPCODES, max_length=30,
                                     null=True)
    backendjobstatus = models.CharField(choices=BACKEND_STATUSES,
                                        max_length=30, null=True)
    backendlogmsg = models.TextField(null=True)
    backendtime = models.DateTimeField(null=False,
                                       default=datetime.datetime.min)

696
697
698
699
    class Meta:
        # Ensure one entry for each network in each backend
        unique_together = (("network", "backend"))

700
701
702
703
704
705
706
707
708
709
710
711
    def __init__(self, *args, **kwargs):
        """Initialize state for just created BackendNetwork instances."""
        super(BackendNetwork, self).__init__(*args, **kwargs)
        if not self.mac_prefix:
            # Generate the MAC prefix of the BackendNetwork, by combining
            # the Network prefix with the index of the Backend
            net_prefix = self.network.mac_prefix
            backend_suffix = hex(self.backend.index).replace('0x', '')
            mac_prefix = net_prefix + backend_suffix
            try:
                utils.validate_mac(mac_prefix + ":00:00:00")
            except utils.InvalidMacAddress:
Christos Stavrakakis's avatar
Christos Stavrakakis committed
712
713
                raise utils.InvalidMacAddress("Invalid MAC prefix '%s'" %
                                              mac_prefix)
714
715
            self.mac_prefix = mac_prefix

716
717
718
    def __unicode__(self):
        return '<%s@%s>' % (self.network, self.backend)

719

720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
class IPAddress(models.Model):
    subnet = models.ForeignKey("Subnet", related_name="ips", null=False,
                               on_delete=models.CASCADE)
    network = models.ForeignKey(Network, related_name="ips", null=False,
                                on_delete=models.CASCADE)
    nic = models.ForeignKey("NetworkInterface", related_name="ips", null=True,
                            on_delete=models.SET_NULL)
    userid = models.CharField("UUID of the owner", max_length=128, null=False,
                              db_index=True)
    address = models.CharField("IP Address", max_length=64, null=False)
    floating_ip = models.BooleanField("Floating IP", null=False, default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    deleted = models.BooleanField(default=False, null=False)

    serial = models.ForeignKey(QuotaHolderSerial,
                               related_name="ips", null=True,
                               on_delete=models.SET_NULL)

    def __unicode__(self):
        ip_type = "floating" if self.floating_ip else "static"
        return u"<IPAddress: %s, Network: %s, Subnet: %s, Type: %s>"\
               % (self.address, self.network_id, self.subnet_id, ip_type)

    def in_use(self):
        if self.machine is None:
            return False
        else:
            return (not self.machine.deleted)

    class Meta:
        unique_together = ("network", "address")

753
754
755
756
757
758
759
760
    @property
    def ipversion(self):
        return self.subnet.ipversion

    @property
    def public(self):
        return self.network.public

761
762
763
764
765
766
767
768
769
    def release_address(self):
        """Release the IPv4 address."""
        if self.ipversion == 4:
            for pool_row in self.subnet.ip_pools.all():
                ip_pool = pool_row.pool
                if ip_pool.contains(self.address):
                    ip_pool.put(self.address)
                    ip_pool.save()

770

771
772
773
class NetworkInterface(models.Model):
    FIREWALL_PROFILES = (
        ('ENABLED', 'Enabled'),
774
775
        ('DISABLED', 'Disabled'),
        ('PROTECTED', 'Protected')
776
    )
777

778
779
780
    STATES = (
        ("ACTIVE", "Active"),
        ("BUILDING", "Building"),
781
        ("ERROR", "Error"),
782
783
    )

784
785
    NETWORK_IFACE_NAME_LENGTH = 128

786
    name = models.CharField('NIC name', max_length=128, null=True)
787
788
    userid = models.CharField("UUID of the owner",
                              max_length=NETWORK_IFACE_NAME_LENGTH,
789
                              null=True, db_index=True)
790
791
792
793
    machine = models.ForeignKey(VirtualMachine, related_name='nics',
                                on_delete=models.CASCADE)
    network = models.ForeignKey(Network, related_name='nics',
                                on_delete=models.CASCADE)
794
795
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
796
    index = models.IntegerField(null=True)
797
    mac = models.CharField(max_length=32, null=True, unique=True)
798
    firewall_profile = models.CharField(choices=FIREWALL_PROFILES,
799
                                        max_length=30, null=True)
800
    security_groups = models.ManyToManyField("SecurityGroup", null=True)
Christos Stavrakakis's avatar
Christos Stavrakakis committed
801
    state = models.CharField(max_length=32, null=False, default="ACTIVE",
802
                             choices=STATES)
803
804
805
806
807
    device_owner = models.CharField('Device owner', max_length=128, null=True)

    def __unicode__(self):
        return "<%s:vm:%s network:%s>" % (self.id, self.machine_id,
                                          self.network_id)
808

809
810
811
812
813
    @property
    def backend_uuid(self):
        """Return the backend id by prepending backend-prefix."""
        return "%snic-%s" % (settings.BACKEND_PREFIX_ID, str(self.id))

814
815
    @property
    def ipv4_address(self):
816
817
818
819
820
821
822
823
824
825
826
        return self.get_ip_address(version=4)

    @property
    def ipv6_address(self):
        return self.get_ip_address(version=6)

    def get_ip_address(self, version=4):
        for ip in self.ips.all():
            if ip.subnet.ipversion == version:
                return ip.address
        return None
827

Marios Kogias's avatar
Marios Kogias committed
828
829
830
    def get_ip_addresses_subnets(self):
        return self.ips.values_list("address", "subnet__id")

831

832
class SecurityGroup(models.Model):
833
834
835
    SECURITY_GROUP_NAME_LENGTH = 128
    name = models.CharField('group name',
                            max_length=SECURITY_GROUP_NAME_LENGTH)
836

837

838
839
840
841
class PoolTable(models.Model):
    available_map = models.TextField(default="", null=False)
    reserved_map = models.TextField(default="", null=False)
    size = models.IntegerField(null=False)
842

843
844
845
    # Optional Fields
    base = models.CharField(null=True, max_length=32)
    offset = models.IntegerField(null=True)
846

847
848
849
850
    class Meta:
        abstract = True

    @classmethod
851
    def get_pool(cls):
852
        try:
853
            pool_row = cls.objects.select_for_update().get()
854
            return pool_row.pool
Christos Stavrakakis's avatar
Christos Stavrakakis committed
855
        except cls.DoesNotExist:
856
            raise pools.EmptyPool
857

858
859
860
    @property
    def pool(self):
        return self.manager(self)
861
862


863
864
class BridgePoolTable(PoolTable):
    manager = pools.BridgePool
865

866
    def __unicode__(self):
867
        return u"<BridgePool id:%s>" % self.id
868

Christos Stavrakakis's avatar
Christos Stavrakakis committed
869

870
871
class MacPrefixPoolTable(PoolTable):
    manager = pools.MacPrefixPool
Christos Stavrakakis's avatar
Christos Stavrakakis committed
872

873
    def __unicode__(self):
874
        return u"<MACPrefixPool id:%s>" % self.id
875

Christos Stavrakakis's avatar
Christos Stavrakakis committed
876
877
878

class IPPoolTable(PoolTable):
    manager = pools.IPPool
879

880
881
    subnet = models.ForeignKey('Subnet', related_name="ip_pools",
                               db_index=True, null=True)
882

883
884
    def __unicode__(self):
        return u"<IPv4AdressPool, Subnet: %s>" % self.subnet_id
885

886

887
888
@contextmanager
def pooled_rapi_client(obj):
889
        if isinstance(obj, (VirtualMachine, BackendNetwork)):
890
891
892
893
894
            backend = obj.backend
        else:
            backend = obj

        if backend.offline:
895
            log.warning("Trying to connect with offline backend: %s", backend)
896
897
            raise faults.ServiceUnavailable("Can not connect to offline"
                                            " backend: %s" % backend)
898
899
900
901

        b = backend
        client = get_rapi_client(b.id, b.hash, b.clustername, b.port,
                                 b.username, b.password)
902
903
904
905
        try:
            yield client
        finally:
            put_rapi_client(client)
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928


class VirtualMachineDiagnosticManager(models.Manager):
    """
    Custom manager for :class:`VirtualMachineDiagnostic` model.
    """

    # diagnostic creation helpers
    def create_for_vm(self, vm, level, message, **kwargs):
        attrs = {'machine': vm, 'level': level, 'message': message}
        attrs.update(kwargs)
        # update instance updated time
        self.create(**attrs)
        vm.save()

    def create_error(self, vm, **kwargs):
        self.create_for_vm(vm, 'ERROR', **kwargs)

    def create_debug(self, vm, **kwargs):
        self.create_for_vm(vm, 'DEBUG', **kwargs)

    def since(self, vm, created_since, **kwargs):
        return self.get_query_set().filter(vm=vm, created__gt=created_since,
Christos Stavrakakis's avatar
Christos Stavrakakis committed
929
                                           **kwargs)
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947


class VirtualMachineDiagnostic(models.Model):
    """
    Model to store backend information messages that relate to the state of
    the virtual machine.
    """

    TYPES = (
        ('ERROR', 'Error'),
        ('WARNING', 'Warning'),
        ('INFO', 'Info'),
        ('DEBUG', 'Debug'),
    )

    objects = VirtualMachineDiagnosticManager()

    created = models.DateTimeField(auto_now_add=True)
948
949
    machine = models.ForeignKey('VirtualMachine', related_name="diagnostics",
                                on_delete=models.CASCADE)
950
951
952
953
954
955
956
957
    level = models.CharField(max_length=20, choices=TYPES)
    source = models.CharField(max_length=100)
    source_date = models.DateTimeField(null=True)
    message = models.CharField(max_length=255)
    details = models.TextField(null=True)

    class Meta:
        ordering = ['-created']