root / snf-cyclades-app / synnefo / db / models.py @ 26515bc1
History | View | Annotate | Download (30.7 kB)
1 |
# Copyright 2011-2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or without
|
4 |
# modification, are permitted provided that the following conditions
|
5 |
# are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above copyright
|
8 |
# notice, this list of conditions and the following disclaimer.
|
9 |
#
|
10 |
# 2. Redistributions in binary form must reproduce the above copyright
|
11 |
# notice, this list of conditions and the following disclaimer in the
|
12 |
# documentation and/or other materials provided with the distribution.
|
13 |
#
|
14 |
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
|
15 |
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
16 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
17 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
|
18 |
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
19 |
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
|
20 |
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
21 |
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
22 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
|
23 |
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
24 |
# SUCH DAMAGE.
|
25 |
#
|
26 |
# The views and conclusions contained in the software and documentation are
|
27 |
# those of the authors and should not be interpreted as representing official
|
28 |
# policies, either expressed or implied, of GRNET S.A.
|
29 |
|
30 |
import datetime |
31 |
|
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 |
from synnefo.logic.rapi_pool import (get_rapi_client, |
46 |
put_rapi_client) |
47 |
|
48 |
import logging |
49 |
log = logging.getLogger(__name__) |
50 |
|
51 |
|
52 |
class Flavor(models.Model): |
53 |
cpu = models.IntegerField('Number of CPUs', default=0) |
54 |
ram = models.IntegerField('RAM size in MiB', default=0) |
55 |
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 |
|
59 |
class Meta: |
60 |
verbose_name = u'Virtual machine flavor'
|
61 |
unique_together = ('cpu', 'ram', 'disk', 'disk_template') |
62 |
|
63 |
@property
|
64 |
def name(self): |
65 |
"""Returns flavor name (generated)"""
|
66 |
return u'C%dR%dD%d%s' % (self.cpu, self.ram, self.disk, |
67 |
self.disk_template)
|
68 |
|
69 |
def __unicode__(self): |
70 |
return "<%s:%s>" % (str(self.id), self.name) |
71 |
|
72 |
|
73 |
class Backend(models.Model): |
74 |
clustername = models.CharField('Cluster Name', max_length=128, unique=True) |
75 |
port = models.PositiveIntegerField('Port', default=5080) |
76 |
username = models.CharField('Username', max_length=64, blank=True, |
77 |
null=True)
|
78 |
password_hash = models.CharField('Password', max_length=128, blank=True, |
79 |
null=True)
|
80 |
# Sha1 is up to 40 characters long
|
81 |
hash = models.CharField('Hash', max_length=40, editable=False, null=False) |
82 |
# Unique index of the Backend, used for the mac-prefixes of the
|
83 |
# BackendNetworks
|
84 |
index = models.PositiveIntegerField('Index', null=False, unique=True, |
85 |
default=0)
|
86 |
drained = models.BooleanField('Drained', default=False, null=False) |
87 |
offline = models.BooleanField('Offline', default=False, null=False) |
88 |
# Type of hypervisor
|
89 |
hypervisor = models.CharField('Hypervisor', max_length=32, default="kvm", |
90 |
null=False)
|
91 |
disk_templates = fields.SeparatedValuesField("Disk Templates", null=True) |
92 |
# Last refresh of backend resources
|
93 |
updated = models.DateTimeField(auto_now_add=True)
|
94 |
# Backend resources
|
95 |
mfree = models.PositiveIntegerField('Free Memory', default=0, null=False) |
96 |
mtotal = models.PositiveIntegerField('Total Memory', default=0, null=False) |
97 |
dfree = models.PositiveIntegerField('Free Disk', default=0, null=False) |
98 |
dtotal = models.PositiveIntegerField('Total Disk', default=0, null=False) |
99 |
pinst_cnt = models.PositiveIntegerField('Primary Instances', default=0, |
100 |
null=False)
|
101 |
ctotal = models.PositiveIntegerField('Total number of logical processors',
|
102 |
default=0, null=False) |
103 |
|
104 |
HYPERVISORS = ( |
105 |
("kvm", "Linux KVM hypervisor"), |
106 |
("xen-pvm", "Xen PVM hypervisor"), |
107 |
("xen-hvm", "Xen KVM hypervisor"), |
108 |
) |
109 |
|
110 |
class Meta: |
111 |
verbose_name = u'Backend'
|
112 |
ordering = ["clustername"]
|
113 |
|
114 |
def __unicode__(self): |
115 |
return self.clustername + "(id=" + str(self.id) + ")" |
116 |
|
117 |
@property
|
118 |
def backend_id(self): |
119 |
return self.id |
120 |
|
121 |
def get_client(self): |
122 |
"""Get or create a client. """
|
123 |
if self.offline: |
124 |
raise faults.ServiceUnavailable
|
125 |
return get_rapi_client(self.id, self.hash, |
126 |
self.clustername,
|
127 |
self.port,
|
128 |
self.username,
|
129 |
self.password)
|
130 |
|
131 |
@staticmethod
|
132 |
def put_client(client): |
133 |
put_rapi_client(client) |
134 |
|
135 |
def create_hash(self): |
136 |
"""Create a hash for this backend. """
|
137 |
sha = sha1('%s%s%s%s' %
|
138 |
(self.clustername, self.port, self.username, self.password)) |
139 |
return sha.hexdigest()
|
140 |
|
141 |
@property
|
142 |
def password(self): |
143 |
return decrypt_db_charfield(self.password_hash) |
144 |
|
145 |
@password.setter
|
146 |
def password(self, value): |
147 |
self.password_hash = encrypt_db_charfield(value)
|
148 |
|
149 |
def save(self, *args, **kwargs): |
150 |
# Create a new hash each time a Backend is saved
|
151 |
old_hash = self.hash
|
152 |
self.hash = self.create_hash() |
153 |
super(Backend, self).save(*args, **kwargs) |
154 |
if self.hash != old_hash: |
155 |
# Populate the new hash to the new instances
|
156 |
self.virtual_machines.filter(deleted=False)\ |
157 |
.update(backend_hash=self.hash)
|
158 |
|
159 |
def __init__(self, *args, **kwargs): |
160 |
super(Backend, self).__init__(*args, **kwargs) |
161 |
if not self.pk: |
162 |
# Generate a unique index for the Backend
|
163 |
indexes = Backend.objects.all().values_list('index', flat=True) |
164 |
try:
|
165 |
first_free = [x for x in xrange(0, 16) if x not in indexes][0] |
166 |
self.index = first_free
|
167 |
except IndexError: |
168 |
raise Exception("Can not create more than 16 backends") |
169 |
|
170 |
def use_hotplug(self): |
171 |
return self.hypervisor == "kvm" and snf_settings.GANETI_USE_HOTPLUG |
172 |
|
173 |
def get_create_params(self): |
174 |
params = deepcopy(snf_settings.GANETI_CREATEINSTANCE_KWARGS) |
175 |
params["hvparams"] = params.get("hvparams", {})\ |
176 |
.get(self.hypervisor, {})
|
177 |
return params
|
178 |
|
179 |
|
180 |
# A backend job may be in one of the following possible states
|
181 |
BACKEND_STATUSES = ( |
182 |
('queued', 'request queued'), |
183 |
('waiting', 'request waiting for locks'), |
184 |
('canceling', 'request being canceled'), |
185 |
('running', 'request running'), |
186 |
('canceled', 'request canceled'), |
187 |
('success', 'request completed successfully'), |
188 |
('error', 'request returned error') |
189 |
) |
190 |
|
191 |
|
192 |
class QuotaHolderSerial(models.Model): |
193 |
"""Model representing a serial for a Quotaholder Commission.
|
194 |
|
195 |
serial: The serial that Quotaholder assigned to this commission
|
196 |
pending: Whether it has been decided to accept or reject this commission
|
197 |
accept: If pending is False, this attribute indicates whether to accept
|
198 |
or reject this commission
|
199 |
resolved: Whether this commission has been accepted or rejected to
|
200 |
Quotaholder.
|
201 |
|
202 |
"""
|
203 |
serial = models.BigIntegerField(null=False, primary_key=True, |
204 |
db_index=True)
|
205 |
pending = models.BooleanField(default=True, db_index=True) |
206 |
accept = models.BooleanField(default=False)
|
207 |
resolved = models.BooleanField(default=False)
|
208 |
|
209 |
class Meta: |
210 |
verbose_name = u'Quota Serial'
|
211 |
ordering = ["serial"]
|
212 |
|
213 |
def __unicode__(self): |
214 |
return u"<serial: %s>" % self.serial |
215 |
|
216 |
|
217 |
class VirtualMachine(models.Model): |
218 |
# The list of possible actions for a VM
|
219 |
ACTIONS = ( |
220 |
('CREATE', 'Create VM'), |
221 |
('START', 'Start VM'), |
222 |
('STOP', 'Shutdown VM'), |
223 |
('SUSPEND', 'Admin Suspend VM'), |
224 |
('REBOOT', 'Reboot VM'), |
225 |
('DESTROY', 'Destroy VM'), |
226 |
('RESIZE', 'Resize a VM'), |
227 |
('ADDFLOATINGIP', 'Add floating IP to VM'), |
228 |
('REMOVEFLOATINGIP', 'Add floating IP to VM'), |
229 |
) |
230 |
|
231 |
# The internal operating state of a VM
|
232 |
OPER_STATES = ( |
233 |
('BUILD', 'Queued for creation'), |
234 |
('ERROR', 'Creation failed'), |
235 |
('STOPPED', 'Stopped'), |
236 |
('STARTED', 'Started'), |
237 |
('DESTROYED', 'Destroyed'), |
238 |
('RESIZE', 'Resizing') |
239 |
) |
240 |
|
241 |
# The list of possible operations on the backend
|
242 |
BACKEND_OPCODES = ( |
243 |
('OP_INSTANCE_CREATE', 'Create Instance'), |
244 |
('OP_INSTANCE_REMOVE', 'Remove Instance'), |
245 |
('OP_INSTANCE_STARTUP', 'Startup Instance'), |
246 |
('OP_INSTANCE_SHUTDOWN', 'Shutdown Instance'), |
247 |
('OP_INSTANCE_REBOOT', 'Reboot Instance'), |
248 |
|
249 |
# These are listed here for completeness,
|
250 |
# and are ignored for the time being
|
251 |
('OP_INSTANCE_SET_PARAMS', 'Set Instance Parameters'), |
252 |
('OP_INSTANCE_QUERY_DATA', 'Query Instance Data'), |
253 |
('OP_INSTANCE_REINSTALL', 'Reinstall Instance'), |
254 |
('OP_INSTANCE_ACTIVATE_DISKS', 'Activate Disks'), |
255 |
('OP_INSTANCE_DEACTIVATE_DISKS', 'Deactivate Disks'), |
256 |
('OP_INSTANCE_REPLACE_DISKS', 'Replace Disks'), |
257 |
('OP_INSTANCE_MIGRATE', 'Migrate Instance'), |
258 |
('OP_INSTANCE_CONSOLE', 'Get Instance Console'), |
259 |
('OP_INSTANCE_RECREATE_DISKS', 'Recreate Disks'), |
260 |
('OP_INSTANCE_FAILOVER', 'Failover Instance') |
261 |
) |
262 |
|
263 |
# The operating state of a VM,
|
264 |
# upon the successful completion of a backend operation.
|
265 |
# IMPORTANT: Make sure all keys have a corresponding
|
266 |
# entry in BACKEND_OPCODES if you update this field, see #1035, #1111.
|
267 |
OPER_STATE_FROM_OPCODE = { |
268 |
'OP_INSTANCE_CREATE': 'STARTED', |
269 |
'OP_INSTANCE_REMOVE': 'DESTROYED', |
270 |
'OP_INSTANCE_STARTUP': 'STARTED', |
271 |
'OP_INSTANCE_SHUTDOWN': 'STOPPED', |
272 |
'OP_INSTANCE_REBOOT': 'STARTED', |
273 |
'OP_INSTANCE_SET_PARAMS': None, |
274 |
'OP_INSTANCE_QUERY_DATA': None, |
275 |
'OP_INSTANCE_REINSTALL': None, |
276 |
'OP_INSTANCE_ACTIVATE_DISKS': None, |
277 |
'OP_INSTANCE_DEACTIVATE_DISKS': None, |
278 |
'OP_INSTANCE_REPLACE_DISKS': None, |
279 |
'OP_INSTANCE_MIGRATE': None, |
280 |
'OP_INSTANCE_CONSOLE': None, |
281 |
'OP_INSTANCE_RECREATE_DISKS': None, |
282 |
'OP_INSTANCE_FAILOVER': None |
283 |
} |
284 |
|
285 |
# This dictionary contains the correspondence between
|
286 |
# internal operating states and Server States as defined
|
287 |
# by the Rackspace API.
|
288 |
RSAPI_STATE_FROM_OPER_STATE = { |
289 |
"BUILD": "BUILD", |
290 |
"ERROR": "ERROR", |
291 |
"STOPPED": "STOPPED", |
292 |
"STARTED": "ACTIVE", |
293 |
'RESIZE': 'RESIZE', |
294 |
'DESTROYED': 'DELETED', |
295 |
} |
296 |
|
297 |
name = models.CharField('Virtual Machine Name', max_length=255) |
298 |
userid = models.CharField('User ID of the owner', max_length=100, |
299 |
db_index=True, null=False) |
300 |
backend = models.ForeignKey(Backend, null=True,
|
301 |
related_name="virtual_machines",
|
302 |
on_delete=models.PROTECT) |
303 |
backend_hash = models.CharField(max_length=128, null=True, editable=False) |
304 |
created = models.DateTimeField(auto_now_add=True)
|
305 |
updated = models.DateTimeField(auto_now=True)
|
306 |
imageid = models.CharField(max_length=100, null=False) |
307 |
hostid = models.CharField(max_length=100)
|
308 |
flavor = models.ForeignKey(Flavor) |
309 |
deleted = models.BooleanField('Deleted', default=False, db_index=True) |
310 |
suspended = models.BooleanField('Administratively Suspended',
|
311 |
default=False)
|
312 |
serial = models.ForeignKey(QuotaHolderSerial, |
313 |
related_name='virtual_machine', null=True) |
314 |
|
315 |
# VM State
|
316 |
# The following fields are volatile data, in the sense
|
317 |
# that they need not be persistent in the DB, but rather
|
318 |
# get generated at runtime by quering Ganeti and applying
|
319 |
# updates received from Ganeti.
|
320 |
|
321 |
# In the future they could be moved to a separate caching layer
|
322 |
# and removed from the database.
|
323 |
# [vkoukis] after discussion with [faidon].
|
324 |
action = models.CharField(choices=ACTIONS, max_length=30, null=True, |
325 |
default=None)
|
326 |
operstate = models.CharField(choices=OPER_STATES, max_length=30,
|
327 |
null=False, default="BUILD") |
328 |
backendjobid = models.PositiveIntegerField(null=True)
|
329 |
backendopcode = models.CharField(choices=BACKEND_OPCODES, max_length=30,
|
330 |
null=True)
|
331 |
backendjobstatus = models.CharField(choices=BACKEND_STATUSES, |
332 |
max_length=30, null=True) |
333 |
backendlogmsg = models.TextField(null=True)
|
334 |
buildpercentage = models.IntegerField(default=0)
|
335 |
backendtime = models.DateTimeField(default=datetime.datetime.min) |
336 |
|
337 |
# Latest action and corresponding Ganeti job ID, for actions issued
|
338 |
# by the API
|
339 |
task = models.CharField(max_length=64, null=True) |
340 |
task_job_id = models.BigIntegerField(null=True)
|
341 |
|
342 |
def get_client(self): |
343 |
if self.backend: |
344 |
return self.backend.get_client() |
345 |
else:
|
346 |
raise faults.ServiceUnavailable
|
347 |
|
348 |
def get_last_diagnostic(self, **filters): |
349 |
try:
|
350 |
return self.diagnostics.filter()[0] |
351 |
except IndexError: |
352 |
return None |
353 |
|
354 |
@staticmethod
|
355 |
def put_client(client): |
356 |
put_rapi_client(client) |
357 |
|
358 |
def save(self, *args, **kwargs): |
359 |
# Store hash for first time saved vm
|
360 |
if (self.id is None or self.backend_hash == '') and self.backend: |
361 |
self.backend_hash = self.backend.hash |
362 |
super(VirtualMachine, self).save(*args, **kwargs) |
363 |
|
364 |
@property
|
365 |
def backend_vm_id(self): |
366 |
"""Returns the backend id for this VM by prepending backend-prefix."""
|
367 |
if not self.id: |
368 |
raise VirtualMachine.InvalidBackendIdError("self.id is None") |
369 |
return "%s%s" % (settings.BACKEND_PREFIX_ID, str(self.id)) |
370 |
|
371 |
class Meta: |
372 |
verbose_name = u'Virtual machine instance'
|
373 |
get_latest_by = 'created'
|
374 |
|
375 |
def __unicode__(self): |
376 |
return "<vm: %s>" % str(self.id) |
377 |
|
378 |
# Error classes
|
379 |
class InvalidBackendIdError(Exception): |
380 |
def __init__(self, value): |
381 |
self.value = value
|
382 |
|
383 |
def __str__(self): |
384 |
return repr(self.value) |
385 |
|
386 |
class InvalidBackendMsgError(Exception): |
387 |
def __init__(self, opcode, status): |
388 |
self.opcode = opcode
|
389 |
self.status = status
|
390 |
|
391 |
def __str__(self): |
392 |
return repr('<opcode: %s, status: %s>' % (self.opcode, |
393 |
self.status))
|
394 |
|
395 |
class InvalidActionError(Exception): |
396 |
def __init__(self, action): |
397 |
self._action = action
|
398 |
|
399 |
def __str__(self): |
400 |
return repr(str(self._action)) |
401 |
|
402 |
|
403 |
class VirtualMachineMetadata(models.Model): |
404 |
meta_key = models.CharField(max_length=50)
|
405 |
meta_value = models.CharField(max_length=500)
|
406 |
vm = models.ForeignKey(VirtualMachine, related_name='metadata')
|
407 |
|
408 |
class Meta: |
409 |
unique_together = (('meta_key', 'vm'),) |
410 |
verbose_name = u'Key-value pair of metadata for a VM.'
|
411 |
|
412 |
def __unicode__(self): |
413 |
return u'%s: %s' % (self.meta_key, self.meta_value) |
414 |
|
415 |
|
416 |
class Network(models.Model): |
417 |
OPER_STATES = ( |
418 |
('PENDING', 'Pending'), # Unused because of lazy networks |
419 |
('ACTIVE', 'Active'), |
420 |
('DELETED', 'Deleted'), |
421 |
('ERROR', 'Error') |
422 |
) |
423 |
|
424 |
ACTIONS = ( |
425 |
('CREATE', 'Create Network'), |
426 |
('DESTROY', 'Destroy Network'), |
427 |
('ADD', 'Add server to Network'), |
428 |
('REMOVE', 'Remove server from Network'), |
429 |
) |
430 |
|
431 |
RSAPI_STATE_FROM_OPER_STATE = { |
432 |
'PENDING': 'PENDING', |
433 |
'ACTIVE': 'ACTIVE', |
434 |
'DELETED': 'DELETED', |
435 |
'ERROR': 'ERROR' |
436 |
} |
437 |
|
438 |
FLAVORS = { |
439 |
'CUSTOM': {
|
440 |
'mode': 'bridged', |
441 |
'link': settings.DEFAULT_BRIDGE,
|
442 |
'mac_prefix': settings.DEFAULT_MAC_PREFIX,
|
443 |
'tags': None, |
444 |
'desc': "Basic flavor used for a bridged network", |
445 |
}, |
446 |
'IP_LESS_ROUTED': {
|
447 |
'mode': 'routed', |
448 |
'link': settings.DEFAULT_ROUTING_TABLE,
|
449 |
'mac_prefix': settings.DEFAULT_MAC_PREFIX,
|
450 |
'tags': 'ip-less-routed', |
451 |
'desc': "Flavor used for an IP-less routed network using" |
452 |
" Proxy ARP",
|
453 |
}, |
454 |
'MAC_FILTERED': {
|
455 |
'mode': 'bridged', |
456 |
'link': settings.DEFAULT_MAC_FILTERED_BRIDGE,
|
457 |
'mac_prefix': 'pool', |
458 |
'tags': 'private-filtered', |
459 |
'desc': "Flavor used for bridged networks that offer isolation" |
460 |
" via filtering packets based on their src "
|
461 |
" MAC (ebtables)",
|
462 |
}, |
463 |
'PHYSICAL_VLAN': {
|
464 |
'mode': 'bridged', |
465 |
'link': 'pool', |
466 |
'mac_prefix': settings.DEFAULT_MAC_PREFIX,
|
467 |
'tags': 'physical-vlan', |
468 |
'desc': "Flavor used for bridged network that offer isolation" |
469 |
" via dedicated physical vlan",
|
470 |
}, |
471 |
} |
472 |
|
473 |
name = models.CharField('Network Name', max_length=128) |
474 |
userid = models.CharField('User ID of the owner', max_length=128, |
475 |
null=True, db_index=True) |
476 |
# subnet will be null for IPv6 only networks
|
477 |
subnet = models.CharField('Subnet', max_length=32, null=True) |
478 |
# subnet6 will be null for IPv4 only networks
|
479 |
subnet6 = models.CharField('IPv6 Subnet', max_length=64, null=True) |
480 |
gateway = models.CharField('Gateway', max_length=32, null=True) |
481 |
gateway6 = models.CharField('IPv6 Gateway', max_length=64, null=True) |
482 |
dhcp = models.BooleanField('DHCP', default=True) |
483 |
flavor = models.CharField('Flavor', max_length=32, null=False) |
484 |
mode = models.CharField('Network Mode', max_length=16, null=True) |
485 |
link = models.CharField('Network Link', max_length=32, null=True) |
486 |
mac_prefix = models.CharField('MAC Prefix', max_length=32, null=False) |
487 |
tags = models.CharField('Network Tags', max_length=128, null=True) |
488 |
public = models.BooleanField(default=False, db_index=True) |
489 |
created = models.DateTimeField(auto_now_add=True)
|
490 |
updated = models.DateTimeField(auto_now=True)
|
491 |
deleted = models.BooleanField('Deleted', default=False, db_index=True) |
492 |
state = models.CharField(choices=OPER_STATES, max_length=32,
|
493 |
default='PENDING')
|
494 |
machines = models.ManyToManyField(VirtualMachine, |
495 |
through='NetworkInterface')
|
496 |
action = models.CharField(choices=ACTIONS, max_length=32, null=True, |
497 |
default=None)
|
498 |
drained = models.BooleanField("Drained", default=False, null=False) |
499 |
floating_ip_pool = models.BooleanField('Floating IP Pool', null=False, |
500 |
default=False)
|
501 |
pool = models.OneToOneField('IPPoolTable', related_name='network', |
502 |
default=lambda: IPPoolTable.objects.create(
|
503 |
available_map='',
|
504 |
reserved_map='',
|
505 |
size=0),
|
506 |
null=True)
|
507 |
serial = models.ForeignKey(QuotaHolderSerial, related_name='network',
|
508 |
null=True)
|
509 |
|
510 |
def __unicode__(self): |
511 |
return "<Network: %s>" % str(self.id) |
512 |
|
513 |
@property
|
514 |
def backend_id(self): |
515 |
"""Return the backend id by prepending backend-prefix."""
|
516 |
if not self.id: |
517 |
raise Network.InvalidBackendIdError("self.id is None") |
518 |
return "%snet-%s" % (settings.BACKEND_PREFIX_ID, str(self.id)) |
519 |
|
520 |
@property
|
521 |
def backend_tag(self): |
522 |
"""Return the network tag to be used in backend
|
523 |
|
524 |
"""
|
525 |
if self.tags: |
526 |
return self.tags.split(',') |
527 |
else:
|
528 |
return []
|
529 |
|
530 |
def create_backend_network(self, backend=None): |
531 |
"""Create corresponding BackendNetwork entries."""
|
532 |
|
533 |
backends = [backend] if backend else\ |
534 |
Backend.objects.filter(offline=False)
|
535 |
for backend in backends: |
536 |
backend_exists =\ |
537 |
BackendNetwork.objects.filter(backend=backend, network=self)\
|
538 |
.exists() |
539 |
if not backend_exists: |
540 |
BackendNetwork.objects.create(backend=backend, network=self)
|
541 |
|
542 |
def get_pool(self, with_lock=True): |
543 |
if not self.pool_id: |
544 |
self.pool = IPPoolTable.objects.create(available_map='', |
545 |
reserved_map='',
|
546 |
size=0)
|
547 |
self.save()
|
548 |
objects = IPPoolTable.objects |
549 |
if with_lock:
|
550 |
objects = objects.select_for_update() |
551 |
return objects.get(id=self.pool_id).pool |
552 |
|
553 |
def reserve_address(self, address): |
554 |
pool = self.get_pool()
|
555 |
pool.reserve(address) |
556 |
pool.save() |
557 |
|
558 |
def release_address(self, address): |
559 |
pool = self.get_pool()
|
560 |
pool.put(address) |
561 |
pool.save() |
562 |
|
563 |
class InvalidBackendIdError(Exception): |
564 |
def __init__(self, value): |
565 |
self.value = value
|
566 |
|
567 |
def __str__(self): |
568 |
return repr(self.value) |
569 |
|
570 |
class InvalidBackendMsgError(Exception): |
571 |
def __init__(self, opcode, status): |
572 |
self.opcode = opcode
|
573 |
self.status = status
|
574 |
|
575 |
def __str__(self): |
576 |
return repr('<opcode: %s, status: %s>' |
577 |
% (self.opcode, self.status)) |
578 |
|
579 |
class InvalidActionError(Exception): |
580 |
def __init__(self, action): |
581 |
self._action = action
|
582 |
|
583 |
def __str__(self): |
584 |
return repr(str(self._action)) |
585 |
|
586 |
|
587 |
class BackendNetwork(models.Model): |
588 |
OPER_STATES = ( |
589 |
('PENDING', 'Pending'), |
590 |
('ACTIVE', 'Active'), |
591 |
('DELETED', 'Deleted'), |
592 |
('ERROR', 'Error') |
593 |
) |
594 |
|
595 |
# The list of possible operations on the backend
|
596 |
BACKEND_OPCODES = ( |
597 |
('OP_NETWORK_ADD', 'Create Network'), |
598 |
('OP_NETWORK_CONNECT', 'Activate Network'), |
599 |
('OP_NETWORK_DISCONNECT', 'Deactivate Network'), |
600 |
('OP_NETWORK_REMOVE', 'Remove Network'), |
601 |
# These are listed here for completeness,
|
602 |
# and are ignored for the time being
|
603 |
('OP_NETWORK_SET_PARAMS', 'Set Network Parameters'), |
604 |
('OP_NETWORK_QUERY_DATA', 'Query Network Data') |
605 |
) |
606 |
|
607 |
# The operating state of a Netowork,
|
608 |
# upon the successful completion of a backend operation.
|
609 |
# IMPORTANT: Make sure all keys have a corresponding
|
610 |
# entry in BACKEND_OPCODES if you update this field, see #1035, #1111.
|
611 |
OPER_STATE_FROM_OPCODE = { |
612 |
'OP_NETWORK_ADD': 'PENDING', |
613 |
'OP_NETWORK_CONNECT': 'ACTIVE', |
614 |
'OP_NETWORK_DISCONNECT': 'PENDING', |
615 |
'OP_NETWORK_REMOVE': 'DELETED', |
616 |
'OP_NETWORK_SET_PARAMS': None, |
617 |
'OP_NETWORK_QUERY_DATA': None |
618 |
} |
619 |
|
620 |
network = models.ForeignKey(Network, related_name='backend_networks')
|
621 |
backend = models.ForeignKey(Backend, related_name='networks',
|
622 |
on_delete=models.PROTECT) |
623 |
created = models.DateTimeField(auto_now_add=True)
|
624 |
updated = models.DateTimeField(auto_now=True)
|
625 |
deleted = models.BooleanField('Deleted', default=False) |
626 |
mac_prefix = models.CharField('MAC Prefix', max_length=32, null=False) |
627 |
operstate = models.CharField(choices=OPER_STATES, max_length=30,
|
628 |
default='PENDING')
|
629 |
backendjobid = models.PositiveIntegerField(null=True)
|
630 |
backendopcode = models.CharField(choices=BACKEND_OPCODES, max_length=30,
|
631 |
null=True)
|
632 |
backendjobstatus = models.CharField(choices=BACKEND_STATUSES, |
633 |
max_length=30, null=True) |
634 |
backendlogmsg = models.TextField(null=True)
|
635 |
backendtime = models.DateTimeField(null=False,
|
636 |
default=datetime.datetime.min) |
637 |
|
638 |
class Meta: |
639 |
# Ensure one entry for each network in each backend
|
640 |
unique_together = (("network", "backend")) |
641 |
|
642 |
def __init__(self, *args, **kwargs): |
643 |
"""Initialize state for just created BackendNetwork instances."""
|
644 |
super(BackendNetwork, self).__init__(*args, **kwargs) |
645 |
if not self.mac_prefix: |
646 |
# Generate the MAC prefix of the BackendNetwork, by combining
|
647 |
# the Network prefix with the index of the Backend
|
648 |
net_prefix = self.network.mac_prefix
|
649 |
backend_suffix = hex(self.backend.index).replace('0x', '') |
650 |
mac_prefix = net_prefix + backend_suffix |
651 |
try:
|
652 |
utils.validate_mac(mac_prefix + ":00:00:00")
|
653 |
except utils.InvalidMacAddress:
|
654 |
raise utils.InvalidMacAddress("Invalid MAC prefix '%s'" % |
655 |
mac_prefix) |
656 |
self.mac_prefix = mac_prefix
|
657 |
|
658 |
def __unicode__(self): |
659 |
return '<%s@%s>' % (self.network, self.backend) |
660 |
|
661 |
|
662 |
class NetworkInterface(models.Model): |
663 |
FIREWALL_PROFILES = ( |
664 |
('ENABLED', 'Enabled'), |
665 |
('DISABLED', 'Disabled'), |
666 |
('PROTECTED', 'Protected') |
667 |
) |
668 |
|
669 |
STATES = ( |
670 |
("ACTIVE", "Active"), |
671 |
("BUILDING", "Building"), |
672 |
("ERROR", "Error"), |
673 |
) |
674 |
|
675 |
machine = models.ForeignKey(VirtualMachine, related_name='nics')
|
676 |
network = models.ForeignKey(Network, related_name='nics')
|
677 |
created = models.DateTimeField(auto_now_add=True)
|
678 |
updated = models.DateTimeField(auto_now=True)
|
679 |
index = models.IntegerField(null=True)
|
680 |
mac = models.CharField(max_length=32, null=True, unique=True) |
681 |
ipv4 = models.CharField(max_length=15, null=True) |
682 |
ipv6 = models.CharField(max_length=100, null=True) |
683 |
firewall_profile = models.CharField(choices=FIREWALL_PROFILES, |
684 |
max_length=30, null=True) |
685 |
dirty = models.BooleanField(default=False)
|
686 |
state = models.CharField(max_length=32, null=False, default="ACTIVE", |
687 |
choices=STATES) |
688 |
|
689 |
def __unicode__(self): |
690 |
return "<%s:vm:%s network:%s ipv4:%s ipv6:%s>" % \ |
691 |
(self.index, self.machine_id, self.network_id, self.ipv4, |
692 |
self.ipv6)
|
693 |
|
694 |
@property
|
695 |
def is_floating_ip(self): |
696 |
network = self.network
|
697 |
if self.ipv4 and network.floating_ip_pool: |
698 |
return network.floating_ips.filter(machine=self.machine, |
699 |
ipv4=self.ipv4,
|
700 |
deleted=False).exists()
|
701 |
return False |
702 |
|
703 |
|
704 |
class FloatingIP(models.Model): |
705 |
userid = models.CharField("UUID of the owner", max_length=128, |
706 |
null=False, db_index=True) |
707 |
ipv4 = models.IPAddressField(null=False, unique=True, db_index=True) |
708 |
network = models.ForeignKey(Network, related_name="floating_ips",
|
709 |
null=False)
|
710 |
machine = models.ForeignKey(VirtualMachine, related_name="floating_ips",
|
711 |
null=True)
|
712 |
created = models.DateTimeField(auto_now_add=True)
|
713 |
deleted = models.BooleanField(default=False, null=False) |
714 |
serial = models.ForeignKey(QuotaHolderSerial, |
715 |
related_name="floating_ips", null=True) |
716 |
|
717 |
def __unicode__(self): |
718 |
return "<FIP: %s@%s>" % (self.ipv4, self.network.id) |
719 |
|
720 |
def in_use(self): |
721 |
if self.machine is None: |
722 |
return False |
723 |
else:
|
724 |
return (not self.machine.deleted) |
725 |
|
726 |
|
727 |
class PoolTable(models.Model): |
728 |
available_map = models.TextField(default="", null=False) |
729 |
reserved_map = models.TextField(default="", null=False) |
730 |
size = models.IntegerField(null=False)
|
731 |
|
732 |
# Optional Fields
|
733 |
base = models.CharField(null=True, max_length=32) |
734 |
offset = models.IntegerField(null=True)
|
735 |
|
736 |
class Meta: |
737 |
abstract = True
|
738 |
|
739 |
@classmethod
|
740 |
def get_pool(cls): |
741 |
try:
|
742 |
pool_row = cls.objects.select_for_update().get() |
743 |
return pool_row.pool
|
744 |
except cls.DoesNotExist:
|
745 |
raise pools.EmptyPool
|
746 |
|
747 |
@property
|
748 |
def pool(self): |
749 |
return self.manager(self) |
750 |
|
751 |
|
752 |
class BridgePoolTable(PoolTable): |
753 |
manager = pools.BridgePool |
754 |
|
755 |
|
756 |
class MacPrefixPoolTable(PoolTable): |
757 |
manager = pools.MacPrefixPool |
758 |
|
759 |
|
760 |
class IPPoolTable(PoolTable): |
761 |
manager = pools.IPPool |
762 |
|
763 |
|
764 |
@contextmanager
|
765 |
def pooled_rapi_client(obj): |
766 |
if isinstance(obj, (VirtualMachine, BackendNetwork)): |
767 |
backend = obj.backend |
768 |
else:
|
769 |
backend = obj |
770 |
|
771 |
if backend.offline:
|
772 |
log.warning("Trying to connect with offline backend: %s", backend)
|
773 |
raise faults.ServiceUnavailable("Can not connect to offline" |
774 |
" backend: %s" % backend)
|
775 |
|
776 |
b = backend |
777 |
client = get_rapi_client(b.id, b.hash, b.clustername, b.port, |
778 |
b.username, b.password) |
779 |
try:
|
780 |
yield client
|
781 |
finally:
|
782 |
put_rapi_client(client) |
783 |
|
784 |
|
785 |
class VirtualMachineDiagnosticManager(models.Manager): |
786 |
"""
|
787 |
Custom manager for :class:`VirtualMachineDiagnostic` model.
|
788 |
"""
|
789 |
|
790 |
# diagnostic creation helpers
|
791 |
def create_for_vm(self, vm, level, message, **kwargs): |
792 |
attrs = {'machine': vm, 'level': level, 'message': message} |
793 |
attrs.update(kwargs) |
794 |
# update instance updated time
|
795 |
self.create(**attrs)
|
796 |
vm.save() |
797 |
|
798 |
def create_error(self, vm, **kwargs): |
799 |
self.create_for_vm(vm, 'ERROR', **kwargs) |
800 |
|
801 |
def create_debug(self, vm, **kwargs): |
802 |
self.create_for_vm(vm, 'DEBUG', **kwargs) |
803 |
|
804 |
def since(self, vm, created_since, **kwargs): |
805 |
return self.get_query_set().filter(vm=vm, created__gt=created_since, |
806 |
**kwargs) |
807 |
|
808 |
|
809 |
class VirtualMachineDiagnostic(models.Model): |
810 |
"""
|
811 |
Model to store backend information messages that relate to the state of
|
812 |
the virtual machine.
|
813 |
"""
|
814 |
|
815 |
TYPES = ( |
816 |
('ERROR', 'Error'), |
817 |
('WARNING', 'Warning'), |
818 |
('INFO', 'Info'), |
819 |
('DEBUG', 'Debug'), |
820 |
) |
821 |
|
822 |
objects = VirtualMachineDiagnosticManager() |
823 |
|
824 |
created = models.DateTimeField(auto_now_add=True)
|
825 |
machine = models.ForeignKey('VirtualMachine', related_name="diagnostics") |
826 |
level = models.CharField(max_length=20, choices=TYPES)
|
827 |
source = models.CharField(max_length=100)
|
828 |
source_date = models.DateTimeField(null=True)
|
829 |
message = models.CharField(max_length=255)
|
830 |
details = models.TextField(null=True)
|
831 |
|
832 |
class Meta: |
833 |
ordering = ['-created']
|