root / snf-cyclades-app / synnefo / db / models.py @ 3416e629
History | View | Annotate | Download (26.4 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 django.conf import settings |
33 |
from django.db import models |
34 |
from django.db import IntegrityError |
35 |
|
36 |
import utils |
37 |
from contextlib import contextmanager |
38 |
from hashlib import sha1 |
39 |
from synnefo.api.faults import ServiceUnavailable |
40 |
from synnefo import settings as snf_settings |
41 |
from aes_encrypt import encrypt_db_charfield, decrypt_db_charfield |
42 |
|
43 |
from synnefo.db.managers import ForUpdateManager, ProtectedDeleteManager |
44 |
from synnefo.db import pools |
45 |
|
46 |
from synnefo.logic.rapi_pool import (get_rapi_client, |
47 |
put_rapi_client) |
48 |
|
49 |
import logging |
50 |
log = logging.getLogger(__name__) |
51 |
|
52 |
|
53 |
class Flavor(models.Model): |
54 |
cpu = models.IntegerField('Number of CPUs', default=0) |
55 |
ram = models.IntegerField('RAM size in MiB', default=0) |
56 |
disk = models.IntegerField('Disk size in GiB', default=0) |
57 |
disk_template = models.CharField('Disk template', max_length=32, |
58 |
default=settings.DEFAULT_GANETI_DISK_TEMPLATE) |
59 |
deleted = models.BooleanField('Deleted', default=False) |
60 |
|
61 |
class Meta: |
62 |
verbose_name = u'Virtual machine flavor'
|
63 |
unique_together = ('cpu', 'ram', 'disk', 'disk_template') |
64 |
|
65 |
@property
|
66 |
def name(self): |
67 |
"""Returns flavor name (generated)"""
|
68 |
return u'C%dR%dD%d' % (self.cpu, self.ram, self.disk) |
69 |
|
70 |
def __unicode__(self): |
71 |
return str(self.id) |
72 |
|
73 |
|
74 |
class Backend(models.Model): |
75 |
clustername = models.CharField('Cluster Name', max_length=128, unique=True) |
76 |
port = models.PositiveIntegerField('Port', default=5080) |
77 |
username = models.CharField('Username', max_length=64, blank=True, |
78 |
null=True)
|
79 |
password_hash = models.CharField('Password', max_length=128, blank=True, |
80 |
null=True)
|
81 |
# Sha1 is up to 40 characters long
|
82 |
hash = models.CharField('Hash', max_length=40, editable=False, null=False) |
83 |
# Unique index of the Backend, used for the mac-prefixes of the
|
84 |
# BackendNetworks
|
85 |
index = models.PositiveIntegerField('Index', null=False, unique=True, |
86 |
default=0)
|
87 |
drained = models.BooleanField('Drained', default=False, null=False) |
88 |
offline = models.BooleanField('Offline', default=False, null=False) |
89 |
# Last refresh of backend resources
|
90 |
updated = models.DateTimeField(auto_now_add=True)
|
91 |
# Backend resources
|
92 |
mfree = models.PositiveIntegerField('Free Memory', default=0, null=False) |
93 |
mtotal = models.PositiveIntegerField('Total Memory', default=0, null=False) |
94 |
dfree = models.PositiveIntegerField('Free Disk', default=0, null=False) |
95 |
dtotal = models.PositiveIntegerField('Total Disk', default=0, null=False) |
96 |
pinst_cnt = models.PositiveIntegerField('Primary Instances', default=0, |
97 |
null=False)
|
98 |
ctotal = models.PositiveIntegerField('Total number of logical processors',
|
99 |
default=0, null=False) |
100 |
# Custom object manager to protect from cascade delete
|
101 |
objects = ProtectedDeleteManager() |
102 |
|
103 |
class Meta: |
104 |
verbose_name = u'Backend'
|
105 |
ordering = ["clustername"]
|
106 |
|
107 |
def __unicode__(self): |
108 |
return self.clustername + "(id=" + str(self.id) + ")" |
109 |
|
110 |
@property
|
111 |
def backend_id(self): |
112 |
return self.id |
113 |
|
114 |
def get_client(self): |
115 |
"""Get or create a client. """
|
116 |
if self.offline: |
117 |
raise ServiceUnavailable
|
118 |
return get_rapi_client(self.id, self.hash, |
119 |
self.clustername,
|
120 |
self.port,
|
121 |
self.username,
|
122 |
self.password)
|
123 |
|
124 |
@staticmethod
|
125 |
def put_client(client): |
126 |
put_rapi_client(client) |
127 |
|
128 |
def create_hash(self): |
129 |
"""Create a hash for this backend. """
|
130 |
return sha1('%s%s%s%s' % \ |
131 |
(self.clustername, self.port, self.username, self.password)) \ |
132 |
.hexdigest() |
133 |
|
134 |
@property
|
135 |
def password(self): |
136 |
return decrypt_db_charfield(self.password_hash) |
137 |
|
138 |
@password.setter
|
139 |
def password(self, value): |
140 |
self.password_hash = encrypt_db_charfield(value)
|
141 |
|
142 |
def save(self, *args, **kwargs): |
143 |
# Create a new hash each time a Backend is saved
|
144 |
old_hash = self.hash
|
145 |
self.hash = self.create_hash() |
146 |
super(Backend, self).save(*args, **kwargs) |
147 |
if self.hash != old_hash: |
148 |
# Populate the new hash to the new instances
|
149 |
self.virtual_machines.filter(deleted=False).update(backend_hash=self.hash) |
150 |
|
151 |
def delete(self, *args, **kwargs): |
152 |
# Integrity Error if non-deleted VMs are associated with Backend
|
153 |
if self.virtual_machines.filter(deleted=False).count(): |
154 |
raise IntegrityError("Non-deleted virtual machines are associated " |
155 |
"with backend: %s" % self) |
156 |
else:
|
157 |
# ON_DELETE = SET NULL
|
158 |
self.virtual_machines.all().backend = None |
159 |
# Remove BackendNetworks of this Backend.
|
160 |
# Do not use networks.all().delete(), since delete() method of
|
161 |
# BackendNetwork will not be called!
|
162 |
for net in self.networks.all(): |
163 |
net.delete() |
164 |
super(Backend, self).delete(*args, **kwargs) |
165 |
|
166 |
def __init__(self, *args, **kwargs): |
167 |
super(Backend, self).__init__(*args, **kwargs) |
168 |
if not self.pk: |
169 |
# Generate a unique index for the Backend
|
170 |
indexes = Backend.objects.all().values_list('index', flat=True) |
171 |
first_free = [x for x in xrange(0, 16) if x not in indexes][0] |
172 |
self.index = first_free
|
173 |
|
174 |
|
175 |
# A backend job may be in one of the following possible states
|
176 |
BACKEND_STATUSES = ( |
177 |
('queued', 'request queued'), |
178 |
('waiting', 'request waiting for locks'), |
179 |
('canceling', 'request being canceled'), |
180 |
('running', 'request running'), |
181 |
('canceled', 'request canceled'), |
182 |
('success', 'request completed successfully'), |
183 |
('error', 'request returned error') |
184 |
) |
185 |
|
186 |
|
187 |
class QuotaHolderSerial(models.Model): |
188 |
serial = models.BigIntegerField(null=False, primary_key=True, db_index=True) |
189 |
pending = models.BooleanField(default=True, db_index=True) |
190 |
accepted = models.BooleanField(default=False)
|
191 |
rejected = models.BooleanField(default=False)
|
192 |
|
193 |
class Meta: |
194 |
verbose_name = u'Quota Serial'
|
195 |
ordering = ["serial"]
|
196 |
|
197 |
def save(self, *args, **kwargs): |
198 |
self.pending = not (self.accepted or self.rejected) |
199 |
super(QuotaHolderSerial, self).save(*args, **kwargs) |
200 |
|
201 |
|
202 |
class VirtualMachine(models.Model): |
203 |
# The list of possible actions for a VM
|
204 |
ACTIONS = ( |
205 |
('CREATE', 'Create VM'), |
206 |
('START', 'Start VM'), |
207 |
('STOP', 'Shutdown VM'), |
208 |
('SUSPEND', 'Admin Suspend VM'), |
209 |
('REBOOT', 'Reboot VM'), |
210 |
('DESTROY', 'Destroy VM') |
211 |
) |
212 |
|
213 |
# The internal operating state of a VM
|
214 |
OPER_STATES = ( |
215 |
('BUILD', 'Queued for creation'), |
216 |
('ERROR', 'Creation failed'), |
217 |
('STOPPED', 'Stopped'), |
218 |
('STARTED', 'Started'), |
219 |
('DESTROYED', 'Destroyed') |
220 |
) |
221 |
|
222 |
# The list of possible operations on the backend
|
223 |
BACKEND_OPCODES = ( |
224 |
('OP_INSTANCE_CREATE', 'Create Instance'), |
225 |
('OP_INSTANCE_REMOVE', 'Remove Instance'), |
226 |
('OP_INSTANCE_STARTUP', 'Startup Instance'), |
227 |
('OP_INSTANCE_SHUTDOWN', 'Shutdown Instance'), |
228 |
('OP_INSTANCE_REBOOT', 'Reboot Instance'), |
229 |
|
230 |
# These are listed here for completeness,
|
231 |
# and are ignored for the time being
|
232 |
('OP_INSTANCE_SET_PARAMS', 'Set Instance Parameters'), |
233 |
('OP_INSTANCE_QUERY_DATA', 'Query Instance Data'), |
234 |
('OP_INSTANCE_REINSTALL', 'Reinstall Instance'), |
235 |
('OP_INSTANCE_ACTIVATE_DISKS', 'Activate Disks'), |
236 |
('OP_INSTANCE_DEACTIVATE_DISKS', 'Deactivate Disks'), |
237 |
('OP_INSTANCE_REPLACE_DISKS', 'Replace Disks'), |
238 |
('OP_INSTANCE_MIGRATE', 'Migrate Instance'), |
239 |
('OP_INSTANCE_CONSOLE', 'Get Instance Console'), |
240 |
('OP_INSTANCE_RECREATE_DISKS', 'Recreate Disks'), |
241 |
('OP_INSTANCE_FAILOVER', 'Failover Instance') |
242 |
) |
243 |
|
244 |
# The operating state of a VM,
|
245 |
# upon the successful completion of a backend operation.
|
246 |
# IMPORTANT: Make sure all keys have a corresponding
|
247 |
# entry in BACKEND_OPCODES if you update this field, see #1035, #1111.
|
248 |
OPER_STATE_FROM_OPCODE = { |
249 |
'OP_INSTANCE_CREATE': 'STARTED', |
250 |
'OP_INSTANCE_REMOVE': 'DESTROYED', |
251 |
'OP_INSTANCE_STARTUP': 'STARTED', |
252 |
'OP_INSTANCE_SHUTDOWN': 'STOPPED', |
253 |
'OP_INSTANCE_REBOOT': 'STARTED', |
254 |
'OP_INSTANCE_SET_PARAMS': None, |
255 |
'OP_INSTANCE_QUERY_DATA': None, |
256 |
'OP_INSTANCE_REINSTALL': None, |
257 |
'OP_INSTANCE_ACTIVATE_DISKS': None, |
258 |
'OP_INSTANCE_DEACTIVATE_DISKS': None, |
259 |
'OP_INSTANCE_REPLACE_DISKS': None, |
260 |
'OP_INSTANCE_MIGRATE': None, |
261 |
'OP_INSTANCE_CONSOLE': None, |
262 |
'OP_INSTANCE_RECREATE_DISKS': None, |
263 |
'OP_INSTANCE_FAILOVER': None |
264 |
} |
265 |
|
266 |
# This dictionary contains the correspondence between
|
267 |
# internal operating states and Server States as defined
|
268 |
# by the Rackspace API.
|
269 |
RSAPI_STATE_FROM_OPER_STATE = { |
270 |
"BUILD": "BUILD", |
271 |
"ERROR": "ERROR", |
272 |
"STOPPED": "STOPPED", |
273 |
"STARTED": "ACTIVE", |
274 |
"DESTROYED": "DELETED" |
275 |
} |
276 |
|
277 |
name = models.CharField('Virtual Machine Name', max_length=255) |
278 |
userid = models.CharField('User ID of the owner', max_length=100, |
279 |
db_index=True)
|
280 |
backend = models.ForeignKey(Backend, null=True,
|
281 |
related_name="virtual_machines",)
|
282 |
backend_hash = models.CharField(max_length=128, null=True, editable=False) |
283 |
created = models.DateTimeField(auto_now_add=True)
|
284 |
updated = models.DateTimeField(auto_now=True)
|
285 |
imageid = models.CharField(max_length=100, null=False) |
286 |
hostid = models.CharField(max_length=100)
|
287 |
flavor = models.ForeignKey(Flavor) |
288 |
deleted = models.BooleanField('Deleted', default=False, db_index=True) |
289 |
suspended = models.BooleanField('Administratively Suspended',
|
290 |
default=False)
|
291 |
|
292 |
# VM State
|
293 |
# The following fields are volatile data, in the sense
|
294 |
# that they need not be persistent in the DB, but rather
|
295 |
# get generated at runtime by quering Ganeti and applying
|
296 |
# updates received from Ganeti.
|
297 |
|
298 |
# In the future they could be moved to a separate caching layer
|
299 |
# and removed from the database.
|
300 |
# [vkoukis] after discussion with [faidon].
|
301 |
action = models.CharField(choices=ACTIONS, max_length=30, null=True) |
302 |
operstate = models.CharField(choices=OPER_STATES, max_length=30, null=True) |
303 |
backendjobid = models.PositiveIntegerField(null=True)
|
304 |
backendopcode = models.CharField(choices=BACKEND_OPCODES, max_length=30,
|
305 |
null=True)
|
306 |
backendjobstatus = models.CharField(choices=BACKEND_STATUSES, |
307 |
max_length=30, null=True) |
308 |
backendlogmsg = models.TextField(null=True)
|
309 |
buildpercentage = models.IntegerField(default=0)
|
310 |
backendtime = models.DateTimeField(default=datetime.datetime.min) |
311 |
|
312 |
objects = ForUpdateManager() |
313 |
|
314 |
def get_client(self): |
315 |
if self.backend: |
316 |
return self.backend.get_client() |
317 |
else:
|
318 |
raise ServiceUnavailable
|
319 |
|
320 |
def get_last_diagnostic(self, **filters): |
321 |
try:
|
322 |
return self.diagnostics.filter()[0] |
323 |
except IndexError: |
324 |
return None |
325 |
|
326 |
@staticmethod
|
327 |
def put_client(client): |
328 |
put_rapi_client(client) |
329 |
|
330 |
def __init__(self, *args, **kw): |
331 |
"""Initialize state for just created VM instances."""
|
332 |
super(VirtualMachine, self).__init__(*args, **kw) |
333 |
# This gets called BEFORE an instance gets save()d for
|
334 |
# the first time.
|
335 |
if not self.pk: |
336 |
self.action = None |
337 |
self.backendjobid = None |
338 |
self.backendjobstatus = None |
339 |
self.backendopcode = None |
340 |
self.backendlogmsg = None |
341 |
self.operstate = 'BUILD' |
342 |
|
343 |
def save(self, *args, **kwargs): |
344 |
# Store hash for first time saved vm
|
345 |
if (self.id is None or self.backend_hash == '') and self.backend: |
346 |
self.backend_hash = self.backend.hash |
347 |
super(VirtualMachine, self).save(*args, **kwargs) |
348 |
|
349 |
@property
|
350 |
def backend_vm_id(self): |
351 |
"""Returns the backend id for this VM by prepending backend-prefix."""
|
352 |
if not self.id: |
353 |
raise VirtualMachine.InvalidBackendIdError("self.id is None") |
354 |
return "%s%s" % (settings.BACKEND_PREFIX_ID, str(self.id)) |
355 |
|
356 |
class Meta: |
357 |
verbose_name = u'Virtual machine instance'
|
358 |
get_latest_by = 'created'
|
359 |
|
360 |
def __unicode__(self): |
361 |
return str(self.id) |
362 |
|
363 |
# Error classes
|
364 |
class InvalidBackendIdError(Exception): |
365 |
def __init__(self, value): |
366 |
self.value = value
|
367 |
|
368 |
def __str__(self): |
369 |
return repr(self.value) |
370 |
|
371 |
class InvalidBackendMsgError(Exception): |
372 |
def __init__(self, opcode, status): |
373 |
self.opcode = opcode
|
374 |
self.status = status
|
375 |
|
376 |
def __str__(self): |
377 |
return repr('<opcode: %s, status: %s>' % (self.opcode, |
378 |
self.status))
|
379 |
|
380 |
class InvalidActionError(Exception): |
381 |
def __init__(self, action): |
382 |
self._action = action
|
383 |
|
384 |
def __str__(self): |
385 |
return repr(str(self._action)) |
386 |
|
387 |
class DeletedError(Exception): |
388 |
pass
|
389 |
|
390 |
class BuildingError(Exception): |
391 |
pass
|
392 |
|
393 |
|
394 |
class VirtualMachineMetadata(models.Model): |
395 |
meta_key = models.CharField(max_length=50)
|
396 |
meta_value = models.CharField(max_length=500)
|
397 |
vm = models.ForeignKey(VirtualMachine, related_name='metadata')
|
398 |
|
399 |
class Meta: |
400 |
unique_together = (('meta_key', 'vm'),) |
401 |
verbose_name = u'Key-value pair of metadata for a VM.'
|
402 |
|
403 |
def __unicode__(self): |
404 |
return u'%s: %s' % (self.meta_key, self.meta_value) |
405 |
|
406 |
|
407 |
class Network(models.Model): |
408 |
OPER_STATES = ( |
409 |
('PENDING', 'Pending'), |
410 |
('ACTIVE', 'Active'), |
411 |
('DELETED', 'Deleted'), |
412 |
('ERROR', 'Error') |
413 |
) |
414 |
|
415 |
ACTIONS = ( |
416 |
('CREATE', 'Create Network'), |
417 |
('DESTROY', 'Destroy Network'), |
418 |
) |
419 |
|
420 |
RSAPI_STATE_FROM_OPER_STATE = { |
421 |
'PENDING': 'PENDING', |
422 |
'ACTIVE': 'ACTIVE', |
423 |
'DELETED': 'DELETED', |
424 |
'ERROR': 'ERROR' |
425 |
} |
426 |
|
427 |
NETWORK_TYPES = ( |
428 |
('PUBLIC_ROUTED', 'Public routed network'), |
429 |
('PRIVATE_PHYSICAL_VLAN', 'Private vlan network'), |
430 |
('PRIVATE_MAC_FILTERED', 'Private network with mac-filtering'), |
431 |
('CUSTOM_ROUTED', 'Custom routed network'), |
432 |
('CUSTOM_BRIDGED', 'Custom bridged network') |
433 |
) |
434 |
|
435 |
name = models.CharField('Network Name', max_length=128) |
436 |
userid = models.CharField('User ID of the owner', max_length=128, |
437 |
null=True, db_index=True) |
438 |
subnet = models.CharField('Subnet', max_length=32, default='10.0.0.0/24') |
439 |
subnet6 = models.CharField('IPv6 Subnet', max_length=64, null=True) |
440 |
gateway = models.CharField('Gateway', max_length=32, null=True) |
441 |
gateway6 = models.CharField('IPv6 Gateway', max_length=64, null=True) |
442 |
dhcp = models.BooleanField('DHCP', default=True) |
443 |
type = models.CharField(choices=NETWORK_TYPES, max_length=50,
|
444 |
default='PRIVATE_PHYSICAL_VLAN')
|
445 |
link = models.CharField('Network Link', max_length=128, null=True) |
446 |
mac_prefix = models.CharField('MAC Prefix', max_length=32, null=False) |
447 |
public = models.BooleanField(default=False, db_index=True) |
448 |
created = models.DateTimeField(auto_now_add=True)
|
449 |
updated = models.DateTimeField(auto_now=True)
|
450 |
deleted = models.BooleanField('Deleted', default=False, db_index=True) |
451 |
state = models.CharField(choices=OPER_STATES, max_length=32,
|
452 |
default='PENDING')
|
453 |
machines = models.ManyToManyField(VirtualMachine, |
454 |
through='NetworkInterface')
|
455 |
action = models.CharField(choices=ACTIONS, max_length=32, null=True, |
456 |
default=None)
|
457 |
|
458 |
pool = models.OneToOneField('IPPoolTable', related_name='network', |
459 |
default=lambda: IPPoolTable.objects.create(available_map='', |
460 |
reserved_map='',
|
461 |
size=0),
|
462 |
null=True)
|
463 |
|
464 |
objects = ForUpdateManager() |
465 |
|
466 |
def __unicode__(self): |
467 |
return str(self.id) |
468 |
|
469 |
@property
|
470 |
def backend_id(self): |
471 |
"""Return the backend id by prepending backend-prefix."""
|
472 |
if not self.id: |
473 |
raise Network.InvalidBackendIdError("self.id is None") |
474 |
return "%snet-%s" % (settings.BACKEND_PREFIX_ID, str(self.id)) |
475 |
|
476 |
@property
|
477 |
def backend_tag(self): |
478 |
"""Return the network tag to be used in backend
|
479 |
|
480 |
"""
|
481 |
return getattr(snf_settings, self.type + '_TAGS') |
482 |
|
483 |
def create_backend_network(self, backend=None): |
484 |
"""Create corresponding BackendNetwork entries."""
|
485 |
|
486 |
backends = [backend] if backend else Backend.objects.all() |
487 |
for backend in backends: |
488 |
BackendNetwork.objects.create(backend=backend, network=self)
|
489 |
|
490 |
def get_pool(self): |
491 |
if not self.pool_id: |
492 |
self.pool = IPPoolTable.objects.create(available_map='', |
493 |
reserved_map='',
|
494 |
size=0)
|
495 |
self.save()
|
496 |
return IPPoolTable.objects.select_for_update().get(id=self.pool_id)\ |
497 |
.pool |
498 |
|
499 |
def reserve_address(self, address): |
500 |
pool = self.get_pool()
|
501 |
pool.reserve(address) |
502 |
pool.save() |
503 |
|
504 |
def release_address(self, address): |
505 |
pool = self.get_pool()
|
506 |
pool.put(address) |
507 |
pool.save() |
508 |
|
509 |
class InvalidBackendIdError(Exception): |
510 |
def __init__(self, value): |
511 |
self.value = value
|
512 |
|
513 |
def __str__(self): |
514 |
return repr(self.value) |
515 |
|
516 |
class InvalidBackendMsgError(Exception): |
517 |
def __init__(self, opcode, status): |
518 |
self.opcode = opcode
|
519 |
self.status = status
|
520 |
|
521 |
def __str__(self): |
522 |
return repr('<opcode: %s, status: %s>' % (self.opcode, |
523 |
self.status))
|
524 |
|
525 |
class InvalidActionError(Exception): |
526 |
def __init__(self, action): |
527 |
self._action = action
|
528 |
|
529 |
def __str__(self): |
530 |
return repr(str(self._action)) |
531 |
|
532 |
|
533 |
class BackendNetwork(models.Model): |
534 |
OPER_STATES = ( |
535 |
('PENDING', 'Pending'), |
536 |
('ACTIVE', 'Active'), |
537 |
('DELETED', 'Deleted'), |
538 |
('ERROR', 'Error') |
539 |
) |
540 |
|
541 |
# The list of possible operations on the backend
|
542 |
BACKEND_OPCODES = ( |
543 |
('OP_NETWORK_ADD', 'Create Network'), |
544 |
('OP_NETWORK_CONNECT', 'Activate Network'), |
545 |
('OP_NETWORK_DISCONNECT', 'Deactivate Network'), |
546 |
('OP_NETWORK_REMOVE', 'Remove Network'), |
547 |
# These are listed here for completeness,
|
548 |
# and are ignored for the time being
|
549 |
('OP_NETWORK_SET_PARAMS', 'Set Network Parameters'), |
550 |
('OP_NETWORK_QUERY_DATA', 'Query Network Data') |
551 |
) |
552 |
|
553 |
# The operating state of a Netowork,
|
554 |
# upon the successful completion of a backend operation.
|
555 |
# IMPORTANT: Make sure all keys have a corresponding
|
556 |
# entry in BACKEND_OPCODES if you update this field, see #1035, #1111.
|
557 |
OPER_STATE_FROM_OPCODE = { |
558 |
'OP_NETWORK_ADD': 'PENDING', |
559 |
'OP_NETWORK_CONNECT': 'ACTIVE', |
560 |
'OP_NETWORK_DISCONNECT': 'PENDING', |
561 |
'OP_NETWORK_REMOVE': 'DELETED', |
562 |
'OP_NETWORK_SET_PARAMS': None, |
563 |
'OP_NETWORK_QUERY_DATA': None |
564 |
} |
565 |
|
566 |
network = models.ForeignKey(Network, related_name='backend_networks')
|
567 |
backend = models.ForeignKey(Backend, related_name='networks')
|
568 |
created = models.DateTimeField(auto_now_add=True)
|
569 |
updated = models.DateTimeField(auto_now=True)
|
570 |
deleted = models.BooleanField('Deleted', default=False) |
571 |
mac_prefix = models.CharField('MAC Prefix', max_length=32, null=False) |
572 |
operstate = models.CharField(choices=OPER_STATES, max_length=30,
|
573 |
default='PENDING')
|
574 |
backendjobid = models.PositiveIntegerField(null=True)
|
575 |
backendopcode = models.CharField(choices=BACKEND_OPCODES, max_length=30,
|
576 |
null=True)
|
577 |
backendjobstatus = models.CharField(choices=BACKEND_STATUSES, |
578 |
max_length=30, null=True) |
579 |
backendlogmsg = models.TextField(null=True)
|
580 |
backendtime = models.DateTimeField(null=False,
|
581 |
default=datetime.datetime.min) |
582 |
|
583 |
class Meta: |
584 |
# Ensure one entry for each network in each backend
|
585 |
unique_together = (("network", "backend")) |
586 |
|
587 |
def __init__(self, *args, **kwargs): |
588 |
"""Initialize state for just created BackendNetwork instances."""
|
589 |
super(BackendNetwork, self).__init__(*args, **kwargs) |
590 |
if not self.mac_prefix: |
591 |
# Generate the MAC prefix of the BackendNetwork, by combining
|
592 |
# the Network prefix with the index of the Backend
|
593 |
net_prefix = self.network.mac_prefix
|
594 |
backend_suffix = hex(self.backend.index).replace('0x', '') |
595 |
mac_prefix = net_prefix + backend_suffix |
596 |
try:
|
597 |
utils.validate_mac(mac_prefix + ":00:00:00")
|
598 |
except utils.InvalidMacAddress:
|
599 |
raise utils.InvalidMacAddress("Invalid MAC prefix '%s'" % \ |
600 |
mac_prefix) |
601 |
self.mac_prefix = mac_prefix
|
602 |
|
603 |
|
604 |
class NetworkInterface(models.Model): |
605 |
FIREWALL_PROFILES = ( |
606 |
('ENABLED', 'Enabled'), |
607 |
('DISABLED', 'Disabled'), |
608 |
('PROTECTED', 'Protected') |
609 |
) |
610 |
|
611 |
machine = models.ForeignKey(VirtualMachine, related_name='nics')
|
612 |
network = models.ForeignKey(Network, related_name='nics')
|
613 |
created = models.DateTimeField(auto_now_add=True)
|
614 |
updated = models.DateTimeField(auto_now=True)
|
615 |
index = models.IntegerField(null=False)
|
616 |
mac = models.CharField(max_length=32, null=False, unique=True) |
617 |
ipv4 = models.CharField(max_length=15, null=True) |
618 |
ipv6 = models.CharField(max_length=100, null=True) |
619 |
firewall_profile = models.CharField(choices=FIREWALL_PROFILES, |
620 |
max_length=30, null=True) |
621 |
dirty = models.BooleanField(default=False)
|
622 |
|
623 |
def __unicode__(self): |
624 |
return '%s@%s' % (self.machine.name, self.network.name) |
625 |
|
626 |
|
627 |
class PoolTable(models.Model): |
628 |
available_map = models.TextField(default="", null=False) |
629 |
reserved_map = models.TextField(default="", null=False) |
630 |
size = models.IntegerField(null=False)
|
631 |
|
632 |
# Optional Fields
|
633 |
base = models.CharField(null=True, max_length=32) |
634 |
offset = models.IntegerField(null=True)
|
635 |
|
636 |
objects = ForUpdateManager() |
637 |
|
638 |
class Meta: |
639 |
abstract = True
|
640 |
|
641 |
@classmethod
|
642 |
def get_pool(cls): |
643 |
try:
|
644 |
pool_row = cls.objects.select_for_update().all()[0]
|
645 |
return pool_row.pool
|
646 |
except IndexError: |
647 |
raise pools.EmptyPool
|
648 |
|
649 |
@property
|
650 |
def pool(self): |
651 |
return self.manager(self) |
652 |
|
653 |
|
654 |
class BridgePoolTable(PoolTable): |
655 |
manager = pools.BridgePool |
656 |
|
657 |
|
658 |
class MacPrefixPoolTable(PoolTable): |
659 |
manager = pools.MacPrefixPool |
660 |
|
661 |
|
662 |
class IPPoolTable(PoolTable): |
663 |
manager = pools.IPPool |
664 |
|
665 |
|
666 |
@contextmanager
|
667 |
def pooled_rapi_client(obj): |
668 |
if isinstance(obj, VirtualMachine): |
669 |
backend = obj.backend |
670 |
else:
|
671 |
backend = obj |
672 |
|
673 |
if backend.offline:
|
674 |
raise ServiceUnavailable
|
675 |
|
676 |
b = backend |
677 |
client = get_rapi_client(b.id, b.hash, b.clustername, b.port, |
678 |
b.username, b.password) |
679 |
try:
|
680 |
yield client
|
681 |
finally:
|
682 |
put_rapi_client(client) |
683 |
|
684 |
|
685 |
class VirtualMachineDiagnosticManager(models.Manager): |
686 |
"""
|
687 |
Custom manager for :class:`VirtualMachineDiagnostic` model.
|
688 |
"""
|
689 |
|
690 |
# diagnostic creation helpers
|
691 |
def create_for_vm(self, vm, level, message, **kwargs): |
692 |
attrs = {'machine': vm, 'level': level, 'message': message} |
693 |
attrs.update(kwargs) |
694 |
# update instance updated time
|
695 |
self.create(**attrs)
|
696 |
vm.save() |
697 |
|
698 |
def create_error(self, vm, **kwargs): |
699 |
self.create_for_vm(vm, 'ERROR', **kwargs) |
700 |
|
701 |
def create_debug(self, vm, **kwargs): |
702 |
self.create_for_vm(vm, 'DEBUG', **kwargs) |
703 |
|
704 |
def since(self, vm, created_since, **kwargs): |
705 |
return self.get_query_set().filter(vm=vm, created__gt=created_since, |
706 |
**kwargs) |
707 |
|
708 |
|
709 |
class VirtualMachineDiagnostic(models.Model): |
710 |
"""
|
711 |
Model to store backend information messages that relate to the state of
|
712 |
the virtual machine.
|
713 |
"""
|
714 |
|
715 |
TYPES = ( |
716 |
('ERROR', 'Error'), |
717 |
('WARNING', 'Warning'), |
718 |
('INFO', 'Info'), |
719 |
('DEBUG', 'Debug'), |
720 |
) |
721 |
|
722 |
objects = VirtualMachineDiagnosticManager() |
723 |
|
724 |
created = models.DateTimeField(auto_now_add=True)
|
725 |
machine = models.ForeignKey('VirtualMachine', related_name="diagnostics") |
726 |
level = models.CharField(max_length=20, choices=TYPES)
|
727 |
source = models.CharField(max_length=100)
|
728 |
source_date = models.DateTimeField(null=True)
|
729 |
message = models.CharField(max_length=255)
|
730 |
details = models.TextField(null=True)
|
731 |
|
732 |
class Meta: |
733 |
ordering = ['-created']
|