root / snf-cyclades-app / synnefo / logic / backend.py @ be4d8aed
History | View | Annotate | Download (26 kB)
1 |
# Copyright 2011 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
import json |
35 |
|
36 |
from django.conf import settings |
37 |
from django.db import transaction |
38 |
from datetime import datetime |
39 |
|
40 |
from synnefo.db.models import (Backend, VirtualMachine, Network, |
41 |
BackendNetwork, BACKEND_STATUSES, |
42 |
pooled_rapi_client, BridgePoolTable, |
43 |
MacPrefixPoolTable, VirtualMachineDiagnostic) |
44 |
from synnefo.logic import utils |
45 |
from synnefo import quotas |
46 |
from synnefo.api.util import release_resource |
47 |
|
48 |
from logging import getLogger |
49 |
log = getLogger(__name__) |
50 |
|
51 |
|
52 |
_firewall_tags = { |
53 |
'ENABLED': settings.GANETI_FIREWALL_ENABLED_TAG,
|
54 |
'DISABLED': settings.GANETI_FIREWALL_DISABLED_TAG,
|
55 |
'PROTECTED': settings.GANETI_FIREWALL_PROTECTED_TAG}
|
56 |
|
57 |
_reverse_tags = dict((v.split(':')[3], k) for k, v in _firewall_tags.items()) |
58 |
|
59 |
|
60 |
@transaction.commit_on_success
|
61 |
def process_op_status(vm, etime, jobid, opcode, status, logmsg): |
62 |
"""Process a job progress notification from the backend
|
63 |
|
64 |
Process an incoming message from the backend (currently Ganeti).
|
65 |
Job notifications with a terminating status (sucess, error, or canceled),
|
66 |
also update the operating state of the VM.
|
67 |
|
68 |
"""
|
69 |
# See #1492, #1031, #1111 why this line has been removed
|
70 |
#if (opcode not in [x[0] for x in VirtualMachine.BACKEND_OPCODES] or
|
71 |
if status not in [x[0] for x in BACKEND_STATUSES]: |
72 |
raise VirtualMachine.InvalidBackendMsgError(opcode, status)
|
73 |
|
74 |
vm.backendjobid = jobid |
75 |
vm.backendjobstatus = status |
76 |
vm.backendopcode = opcode |
77 |
vm.backendlogmsg = logmsg |
78 |
|
79 |
# Notifications of success change the operating state
|
80 |
state_for_success = VirtualMachine.OPER_STATE_FROM_OPCODE.get(opcode, None)
|
81 |
if status == 'success' and state_for_success is not None: |
82 |
vm.operstate = state_for_success |
83 |
|
84 |
# Special case: if OP_INSTANCE_CREATE fails --> ERROR
|
85 |
if opcode == 'OP_INSTANCE_CREATE' and status in ('canceled', 'error'): |
86 |
vm.operstate = 'ERROR'
|
87 |
vm.backendtime = etime |
88 |
elif opcode == 'OP_INSTANCE_REMOVE': |
89 |
# Set the deleted flag explicitly, cater for admin-initiated removals
|
90 |
# Special case: OP_INSTANCE_REMOVE fails for machines in ERROR,
|
91 |
# when no instance exists at the Ganeti backend.
|
92 |
# See ticket #799 for all the details.
|
93 |
#
|
94 |
if status == 'success' or (status == 'error' and |
95 |
vm.operstate == 'ERROR'):
|
96 |
release_instance_nics(vm) |
97 |
vm.nics.all().delete() |
98 |
vm.deleted = True
|
99 |
vm.operstate = state_for_success |
100 |
vm.backendtime = etime |
101 |
# Issue and accept commission to Quotaholder
|
102 |
quotas.issue_and_accept_commission(vm, delete=True)
|
103 |
|
104 |
# Update backendtime only for jobs that have been successfully completed,
|
105 |
# since only these jobs update the state of the VM. Else a "race condition"
|
106 |
# may occur when a successful job (e.g. OP_INSTANCE_REMOVE) completes
|
107 |
# before an error job and messages arrive in reversed order.
|
108 |
if status == 'success': |
109 |
vm.backendtime = etime |
110 |
|
111 |
vm.save() |
112 |
|
113 |
|
114 |
@transaction.commit_on_success
|
115 |
def process_net_status(vm, etime, nics): |
116 |
"""Process a net status notification from the backend
|
117 |
|
118 |
Process an incoming message from the Ganeti backend,
|
119 |
detailing the NIC configuration of a VM instance.
|
120 |
|
121 |
Update the state of the VM in the DB accordingly.
|
122 |
"""
|
123 |
|
124 |
ganeti_nics = process_ganeti_nics(nics) |
125 |
if not nics_changed(vm.nics.order_by('index'), ganeti_nics): |
126 |
log.debug("NICs for VM %s have not changed", vm)
|
127 |
|
128 |
release_instance_nics(vm) |
129 |
|
130 |
for nic in ganeti_nics: |
131 |
ipv4 = nic.get('ipv4', '') |
132 |
net = nic['network']
|
133 |
if ipv4:
|
134 |
net.reserve_address(ipv4) |
135 |
|
136 |
nic['dirty'] = False |
137 |
vm.nics.create(**nic) |
138 |
# Dummy save the network, because UI uses changed-since for VMs
|
139 |
# and Networks in order to show the VM NICs
|
140 |
net.save() |
141 |
|
142 |
vm.backendtime = etime |
143 |
vm.save() |
144 |
|
145 |
|
146 |
def process_ganeti_nics(ganeti_nics): |
147 |
"""Process NIC dict from ganeti hooks."""
|
148 |
new_nics = [] |
149 |
for i, new_nic in enumerate(ganeti_nics): |
150 |
network = new_nic.get('network', '') |
151 |
n = str(network)
|
152 |
pk = utils.id_from_network_name(n) |
153 |
|
154 |
net = Network.objects.get(pk=pk) |
155 |
|
156 |
# Get the new nic info
|
157 |
mac = new_nic.get('mac', '') |
158 |
ipv4 = new_nic.get('ip', '') |
159 |
ipv6 = new_nic.get('ipv6', '') |
160 |
|
161 |
firewall = new_nic.get('firewall', '') |
162 |
firewall_profile = _reverse_tags.get(firewall, '')
|
163 |
if not firewall_profile and net.public: |
164 |
firewall_profile = settings.DEFAULT_FIREWALL_PROFILE |
165 |
|
166 |
nic = { |
167 |
'index': i,
|
168 |
'network': net,
|
169 |
'mac': mac,
|
170 |
'ipv4': ipv4,
|
171 |
'ipv6': ipv6,
|
172 |
'firewall_profile': firewall_profile,
|
173 |
'state': 'ACTIVE'} |
174 |
|
175 |
new_nics.append(nic) |
176 |
return new_nics
|
177 |
|
178 |
|
179 |
def nics_changed(old_nics, new_nics): |
180 |
"""Return True if NICs have changed in any way."""
|
181 |
if len(old_nics) != len(new_nics): |
182 |
return True |
183 |
fields = ["ipv4", "ipv6", "mac", "firewall_profile", "index", "network"] |
184 |
for old_nic, new_nic in zip(old_nics, new_nics): |
185 |
for field in fields: |
186 |
if getattr(old_nic, field) != new_nic[field]: |
187 |
return True |
188 |
return False |
189 |
|
190 |
|
191 |
def release_instance_nics(vm): |
192 |
for nic in vm.nics.all(): |
193 |
net = nic.network |
194 |
if nic.ipv4:
|
195 |
net.release_address(nic.ipv4) |
196 |
nic.delete() |
197 |
net.save() |
198 |
|
199 |
|
200 |
@transaction.commit_on_success
|
201 |
def process_network_status(back_network, etime, jobid, opcode, status, logmsg): |
202 |
if status not in [x[0] for x in BACKEND_STATUSES]: |
203 |
raise Network.InvalidBackendMsgError(opcode, status)
|
204 |
|
205 |
back_network.backendjobid = jobid |
206 |
back_network.backendjobstatus = status |
207 |
back_network.backendopcode = opcode |
208 |
back_network.backendlogmsg = logmsg |
209 |
|
210 |
# Notifications of success change the operating state
|
211 |
state_for_success = BackendNetwork.OPER_STATE_FROM_OPCODE.get(opcode, None)
|
212 |
if status == 'success' and state_for_success is not None: |
213 |
back_network.operstate = state_for_success |
214 |
|
215 |
if status in ('canceled', 'error') and opcode == 'OP_NETWORK_ADD': |
216 |
back_network.operstate = 'ERROR'
|
217 |
back_network.backendtime = etime |
218 |
|
219 |
if opcode == 'OP_NETWORK_REMOVE': |
220 |
if status == 'success' or (status == 'error' and |
221 |
back_network.operstate == 'ERROR'):
|
222 |
back_network.operstate = state_for_success |
223 |
back_network.deleted = True
|
224 |
back_network.backendtime = etime |
225 |
|
226 |
if status == 'success': |
227 |
back_network.backendtime = etime |
228 |
back_network.save() |
229 |
# Also you must update the state of the Network!!
|
230 |
update_network_state(back_network.network) |
231 |
|
232 |
|
233 |
def update_network_state(network): |
234 |
"""Update the state of a Network based on BackendNetwork states.
|
235 |
|
236 |
Update the state of a Network based on the operstate of the networks in the
|
237 |
backends that network exists.
|
238 |
|
239 |
The state of the network is:
|
240 |
* ACTIVE: If it is 'ACTIVE' in at least one backend.
|
241 |
* DELETED: If it is is 'DELETED' in all backends that have been created.
|
242 |
|
243 |
This function also releases the resources (MAC prefix or Bridge) and the
|
244 |
quotas for the network.
|
245 |
|
246 |
"""
|
247 |
if network.deleted:
|
248 |
# Network has already been deleted. Just assert that state is also
|
249 |
# DELETED
|
250 |
if not network.state == "DELETED": |
251 |
network.state = "DELETED"
|
252 |
network.save() |
253 |
return
|
254 |
|
255 |
backend_states = [s.operstate for s in network.backend_networks.all()] |
256 |
if not backend_states and network.action != "DESTROY": |
257 |
if network.state != "ACTIVE": |
258 |
network.state = "ACTIVE"
|
259 |
network.save() |
260 |
return
|
261 |
|
262 |
# Network is deleted when all BackendNetworks go to "DELETED" operstate
|
263 |
deleted = reduce(lambda x, y: x == y and "DELETED", backend_states, |
264 |
"DELETED")
|
265 |
|
266 |
# Release the resources on the deletion of the Network
|
267 |
if deleted:
|
268 |
log.info("Network %r deleted. Releasing link %r mac_prefix %r",
|
269 |
network.id, network.mac_prefix, network.link) |
270 |
network.deleted = True
|
271 |
network.state = "DELETED"
|
272 |
if network.mac_prefix:
|
273 |
if network.FLAVORS[network.flavor]["mac_prefix"] == "pool": |
274 |
release_resource(res_type="mac_prefix",
|
275 |
value=network.mac_prefix) |
276 |
if network.link:
|
277 |
if network.FLAVORS[network.flavor]["link"] == "pool": |
278 |
release_resource(res_type="bridge", value=network.link)
|
279 |
|
280 |
# Issue commission
|
281 |
if network.userid:
|
282 |
quotas.issue_and_accept_commission(network, delete=True)
|
283 |
elif not network.public: |
284 |
log.warning("Network %s does not have an owner!", network.id)
|
285 |
network.save() |
286 |
|
287 |
|
288 |
@transaction.commit_on_success
|
289 |
def process_network_modify(back_network, etime, jobid, opcode, status, |
290 |
add_reserved_ips, remove_reserved_ips): |
291 |
assert (opcode == "OP_NETWORK_SET_PARAMS") |
292 |
if status not in [x[0] for x in BACKEND_STATUSES]: |
293 |
raise Network.InvalidBackendMsgError(opcode, status)
|
294 |
|
295 |
back_network.backendjobid = jobid |
296 |
back_network.backendjobstatus = status |
297 |
back_network.opcode = opcode |
298 |
|
299 |
if add_reserved_ips or remove_reserved_ips: |
300 |
net = back_network.network |
301 |
pool = net.get_pool() |
302 |
if add_reserved_ips:
|
303 |
for ip in add_reserved_ips: |
304 |
pool.reserve(ip, external=True)
|
305 |
if remove_reserved_ips:
|
306 |
for ip in remove_reserved_ips: |
307 |
pool.put(ip, external=True)
|
308 |
pool.save() |
309 |
|
310 |
if status == 'success': |
311 |
back_network.backendtime = etime |
312 |
back_network.save() |
313 |
|
314 |
|
315 |
@transaction.commit_on_success
|
316 |
def process_create_progress(vm, etime, progress): |
317 |
|
318 |
percentage = int(progress)
|
319 |
|
320 |
# The percentage may exceed 100%, due to the way
|
321 |
# snf-image:copy-progress tracks bytes read by image handling processes
|
322 |
percentage = 100 if percentage > 100 else percentage |
323 |
if percentage < 0: |
324 |
raise ValueError("Percentage cannot be negative") |
325 |
|
326 |
# FIXME: log a warning here, see #1033
|
327 |
# if last_update > percentage:
|
328 |
# raise ValueError("Build percentage should increase monotonically " \
|
329 |
# "(old = %d, new = %d)" % (last_update, percentage))
|
330 |
|
331 |
# This assumes that no message of type 'ganeti-create-progress' is going to
|
332 |
# arrive once OP_INSTANCE_CREATE has succeeded for a Ganeti instance and
|
333 |
# the instance is STARTED. What if the two messages are processed by two
|
334 |
# separate dispatcher threads, and the 'ganeti-op-status' message for
|
335 |
# successful creation gets processed before the 'ganeti-create-progress'
|
336 |
# message? [vkoukis]
|
337 |
#
|
338 |
#if not vm.operstate == 'BUILD':
|
339 |
# raise VirtualMachine.IllegalState("VM is not in building state")
|
340 |
|
341 |
vm.buildpercentage = percentage |
342 |
vm.backendtime = etime |
343 |
vm.save() |
344 |
|
345 |
|
346 |
def create_instance_diagnostic(vm, message, source, level="DEBUG", etime=None, |
347 |
details=None):
|
348 |
"""
|
349 |
Create virtual machine instance diagnostic entry.
|
350 |
|
351 |
:param vm: VirtualMachine instance to create diagnostic for.
|
352 |
:param message: Diagnostic message.
|
353 |
:param source: Diagnostic source identifier (e.g. image-helper).
|
354 |
:param level: Diagnostic level (`DEBUG`, `INFO`, `WARNING`, `ERROR`).
|
355 |
:param etime: The time the message occured (if available).
|
356 |
:param details: Additional details or debug information.
|
357 |
"""
|
358 |
VirtualMachineDiagnostic.objects.create_for_vm(vm, level, source=source, |
359 |
source_date=etime, |
360 |
message=message, |
361 |
details=details) |
362 |
|
363 |
|
364 |
def create_instance(vm, public_nic, flavor, image): |
365 |
"""`image` is a dictionary which should contain the keys:
|
366 |
'backend_id', 'format' and 'metadata'
|
367 |
|
368 |
metadata value should be a dictionary.
|
369 |
"""
|
370 |
|
371 |
# Handle arguments to CreateInstance() as a dictionary,
|
372 |
# initialize it based on a deployment-specific value.
|
373 |
# This enables the administrator to override deployment-specific
|
374 |
# arguments, such as the disk template to use, name of os provider
|
375 |
# and hypervisor-specific parameters at will (see Synnefo #785, #835).
|
376 |
#
|
377 |
kw = settings.GANETI_CREATEINSTANCE_KWARGS |
378 |
kw['mode'] = 'create' |
379 |
kw['name'] = vm.backend_vm_id
|
380 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
381 |
|
382 |
kw['disk_template'] = flavor.disk_template
|
383 |
kw['disks'] = [{"size": flavor.disk * 1024}] |
384 |
provider = flavor.disk_provider |
385 |
if provider:
|
386 |
kw['disks'][0]['provider'] = provider |
387 |
|
388 |
if provider == 'vlmc': |
389 |
kw['disks'][0]['origin'] = flavor.disk_origin |
390 |
|
391 |
kw['nics'] = [public_nic]
|
392 |
if settings.GANETI_USE_HOTPLUG:
|
393 |
kw['hotplug'] = True |
394 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
395 |
# kw['os'] = settings.GANETI_OS_PROVIDER
|
396 |
kw['ip_check'] = False |
397 |
kw['name_check'] = False |
398 |
|
399 |
# Do not specific a node explicitly, have
|
400 |
# Ganeti use an iallocator instead
|
401 |
#kw['pnode'] = rapi.GetNodes()[0]
|
402 |
|
403 |
kw['dry_run'] = settings.TEST
|
404 |
|
405 |
kw['beparams'] = {
|
406 |
'auto_balance': True, |
407 |
'vcpus': flavor.cpu,
|
408 |
'memory': flavor.ram}
|
409 |
|
410 |
kw['osparams'] = {
|
411 |
'config_url': vm.config_url,
|
412 |
# Store image id and format to Ganeti
|
413 |
'img_id': image['backend_id'], |
414 |
'img_format': image['format']} |
415 |
|
416 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
417 |
# kw['hvparams'] = dict(serial_console=False)
|
418 |
|
419 |
log.debug("Creating instance %s", utils.hide_pass(kw))
|
420 |
with pooled_rapi_client(vm) as client: |
421 |
return client.CreateInstance(**kw)
|
422 |
|
423 |
|
424 |
def delete_instance(vm): |
425 |
with pooled_rapi_client(vm) as client: |
426 |
return client.DeleteInstance(vm.backend_vm_id, dry_run=settings.TEST)
|
427 |
|
428 |
|
429 |
def reboot_instance(vm, reboot_type): |
430 |
assert reboot_type in ('soft', 'hard') |
431 |
with pooled_rapi_client(vm) as client: |
432 |
return client.RebootInstance(vm.backend_vm_id, reboot_type,
|
433 |
dry_run=settings.TEST) |
434 |
|
435 |
|
436 |
def startup_instance(vm): |
437 |
with pooled_rapi_client(vm) as client: |
438 |
return client.StartupInstance(vm.backend_vm_id, dry_run=settings.TEST)
|
439 |
|
440 |
|
441 |
def shutdown_instance(vm): |
442 |
with pooled_rapi_client(vm) as client: |
443 |
return client.ShutdownInstance(vm.backend_vm_id, dry_run=settings.TEST)
|
444 |
|
445 |
|
446 |
def get_instance_console(vm): |
447 |
# RAPI GetInstanceConsole() returns endpoints to the vnc_bind_address,
|
448 |
# which is a cluster-wide setting, either 0.0.0.0 or 127.0.0.1, and pretty
|
449 |
# useless (see #783).
|
450 |
#
|
451 |
# Until this is fixed on the Ganeti side, construct a console info reply
|
452 |
# directly.
|
453 |
#
|
454 |
# WARNING: This assumes that VNC runs on port network_port on
|
455 |
# the instance's primary node, and is probably
|
456 |
# hypervisor-specific.
|
457 |
#
|
458 |
log.debug("Getting console for vm %s", vm)
|
459 |
|
460 |
console = {} |
461 |
console['kind'] = 'vnc' |
462 |
|
463 |
with pooled_rapi_client(vm) as client: |
464 |
i = client.GetInstance(vm.backend_vm_id) |
465 |
|
466 |
if i['hvparams']['serial_console']: |
467 |
raise Exception("hv parameter serial_console cannot be true") |
468 |
console['host'] = i['pnode'] |
469 |
console['port'] = i['network_port'] |
470 |
|
471 |
return console
|
472 |
|
473 |
|
474 |
def get_instance_info(vm): |
475 |
with pooled_rapi_client(vm) as client: |
476 |
return client.GetInstanceInfo(vm.backend_vm_id)
|
477 |
|
478 |
|
479 |
def create_network(network, backend, connect=True): |
480 |
"""Create a network in a Ganeti backend"""
|
481 |
log.debug("Creating network %s in backend %s", network, backend)
|
482 |
|
483 |
job_id = _create_network(network, backend) |
484 |
|
485 |
if connect:
|
486 |
job_ids = connect_network(network, backend, depends=[job_id]) |
487 |
return job_ids
|
488 |
else:
|
489 |
return [job_id]
|
490 |
|
491 |
|
492 |
def _create_network(network, backend): |
493 |
"""Create a network."""
|
494 |
|
495 |
network_type = network.public and 'public' or 'private' |
496 |
|
497 |
tags = network.backend_tag |
498 |
if network.dhcp:
|
499 |
tags.append('nfdhcpd')
|
500 |
|
501 |
if network.public:
|
502 |
conflicts_check = True
|
503 |
else:
|
504 |
conflicts_check = False
|
505 |
|
506 |
try:
|
507 |
bn = BackendNetwork.objects.get(network=network, backend=backend) |
508 |
mac_prefix = bn.mac_prefix |
509 |
except BackendNetwork.DoesNotExist:
|
510 |
raise Exception("BackendNetwork for network '%s' in backend '%s'" |
511 |
" does not exist" % (network.id, backend.id))
|
512 |
|
513 |
with pooled_rapi_client(backend) as client: |
514 |
return client.CreateNetwork(network_name=network.backend_id,
|
515 |
network=network.subnet, |
516 |
network6=network.subnet6, |
517 |
gateway=network.gateway, |
518 |
gateway6=network.gateway6, |
519 |
network_type=network_type, |
520 |
mac_prefix=mac_prefix, |
521 |
conflicts_check=conflicts_check, |
522 |
tags=tags) |
523 |
|
524 |
|
525 |
def connect_network(network, backend, depends=[], group=None): |
526 |
"""Connect a network to nodegroups."""
|
527 |
log.debug("Connecting network %s to backend %s", network, backend)
|
528 |
|
529 |
if network.public:
|
530 |
conflicts_check = True
|
531 |
else:
|
532 |
conflicts_check = False
|
533 |
|
534 |
depends = [[job, ["success", "error", "canceled"]] for job in depends] |
535 |
with pooled_rapi_client(backend) as client: |
536 |
groups = [group] if group is not None else client.GetGroups() |
537 |
job_ids = [] |
538 |
for group in groups: |
539 |
job_id = client.ConnectNetwork(network.backend_id, group, |
540 |
network.mode, network.link, |
541 |
conflicts_check, |
542 |
depends=depends) |
543 |
job_ids.append(job_id) |
544 |
return job_ids
|
545 |
|
546 |
|
547 |
def delete_network(network, backend, disconnect=True): |
548 |
log.debug("Deleting network %s from backend %s", network, backend)
|
549 |
|
550 |
depends = [] |
551 |
if disconnect:
|
552 |
depends = disconnect_network(network, backend) |
553 |
_delete_network(network, backend, depends=depends) |
554 |
|
555 |
|
556 |
def _delete_network(network, backend, depends=[]): |
557 |
depends = [[job, ["success", "error", "canceled"]] for job in depends] |
558 |
with pooled_rapi_client(backend) as client: |
559 |
return client.DeleteNetwork(network.backend_id, depends)
|
560 |
|
561 |
|
562 |
def disconnect_network(network, backend, group=None): |
563 |
log.debug("Disconnecting network %s to backend %s", network, backend)
|
564 |
|
565 |
with pooled_rapi_client(backend) as client: |
566 |
groups = [group] if group is not None else client.GetGroups() |
567 |
job_ids = [] |
568 |
for group in groups: |
569 |
job_id = client.DisconnectNetwork(network.backend_id, group) |
570 |
job_ids.append(job_id) |
571 |
return job_ids
|
572 |
|
573 |
|
574 |
def connect_to_network(vm, network, address=None): |
575 |
backend = vm.backend |
576 |
network = Network.objects.select_for_update().get(id=network.id) |
577 |
bnet, created = BackendNetwork.objects.get_or_create(backend=backend, |
578 |
network=network) |
579 |
depend_jobs = [] |
580 |
if bnet.operstate != "ACTIVE": |
581 |
depend_jobs = create_network(network, backend, connect=True)
|
582 |
|
583 |
depends = [[job, ["success", "error", "canceled"]] for job in depend_jobs] |
584 |
|
585 |
nic = {'ip': address, 'network': network.backend_id} |
586 |
|
587 |
log.debug("Connecting vm %s to network %s(%s)", vm, network, address)
|
588 |
|
589 |
with pooled_rapi_client(vm) as client: |
590 |
return client.ModifyInstance(vm.backend_vm_id, nics=[('add', nic)], |
591 |
hotplug=settings.GANETI_USE_HOTPLUG, |
592 |
depends=depends, |
593 |
dry_run=settings.TEST) |
594 |
|
595 |
|
596 |
def disconnect_from_network(vm, nic): |
597 |
op = [('remove', nic.index, {})]
|
598 |
|
599 |
log.debug("Removing nic of VM %s, with index %s", vm, str(nic.index)) |
600 |
|
601 |
with pooled_rapi_client(vm) as client: |
602 |
return client.ModifyInstance(vm.backend_vm_id, nics=op,
|
603 |
hotplug=settings.GANETI_USE_HOTPLUG, |
604 |
dry_run=settings.TEST) |
605 |
|
606 |
|
607 |
def set_firewall_profile(vm, profile): |
608 |
try:
|
609 |
tag = _firewall_tags[profile] |
610 |
except KeyError: |
611 |
raise ValueError("Unsopported Firewall Profile: %s" % profile) |
612 |
|
613 |
log.debug("Setting tag of VM %s to %s", vm, profile)
|
614 |
|
615 |
with pooled_rapi_client(vm) as client: |
616 |
# Delete all firewall tags
|
617 |
for t in _firewall_tags.values(): |
618 |
client.DeleteInstanceTags(vm.backend_vm_id, [t], |
619 |
dry_run=settings.TEST) |
620 |
|
621 |
client.AddInstanceTags(vm.backend_vm_id, [tag], dry_run=settings.TEST) |
622 |
|
623 |
# XXX NOP ModifyInstance call to force process_net_status to run
|
624 |
# on the dispatcher
|
625 |
os_name = settings.GANETI_CREATEINSTANCE_KWARGS['os']
|
626 |
client.ModifyInstance(vm.backend_vm_id, |
627 |
os_name=os_name) |
628 |
|
629 |
|
630 |
def get_ganeti_instances(backend=None, bulk=False): |
631 |
instances = [] |
632 |
for backend in get_backends(backend): |
633 |
with pooled_rapi_client(backend) as client: |
634 |
instances.append(client.GetInstances(bulk=bulk)) |
635 |
|
636 |
return reduce(list.__add__, instances, []) |
637 |
|
638 |
|
639 |
def get_ganeti_nodes(backend=None, bulk=False): |
640 |
nodes = [] |
641 |
for backend in get_backends(backend): |
642 |
with pooled_rapi_client(backend) as client: |
643 |
nodes.append(client.GetNodes(bulk=bulk)) |
644 |
|
645 |
return reduce(list.__add__, nodes, []) |
646 |
|
647 |
|
648 |
def get_ganeti_jobs(backend=None, bulk=False): |
649 |
jobs = [] |
650 |
for backend in get_backends(backend): |
651 |
with pooled_rapi_client(backend) as client: |
652 |
jobs.append(client.GetJobs(bulk=bulk)) |
653 |
return reduce(list.__add__, jobs, []) |
654 |
|
655 |
##
|
656 |
##
|
657 |
##
|
658 |
|
659 |
|
660 |
def get_backends(backend=None): |
661 |
if backend:
|
662 |
if backend.offline:
|
663 |
return []
|
664 |
return [backend]
|
665 |
return Backend.objects.filter(offline=False) |
666 |
|
667 |
|
668 |
def get_physical_resources(backend): |
669 |
""" Get the physical resources of a backend.
|
670 |
|
671 |
Get the resources of a backend as reported by the backend (not the db).
|
672 |
|
673 |
"""
|
674 |
nodes = get_ganeti_nodes(backend, bulk=True)
|
675 |
attr = ['mfree', 'mtotal', 'dfree', 'dtotal', 'pinst_cnt', 'ctotal'] |
676 |
res = {} |
677 |
for a in attr: |
678 |
res[a] = 0
|
679 |
for n in nodes: |
680 |
# Filter out drained, offline and not vm_capable nodes since they will
|
681 |
# not take part in the vm allocation process
|
682 |
can_host_vms = n['vm_capable'] and not (n['drained'] or n['offline']) |
683 |
if can_host_vms and n['cnodes']: |
684 |
for a in attr: |
685 |
res[a] += int(n[a])
|
686 |
return res
|
687 |
|
688 |
|
689 |
def update_resources(backend, resources=None): |
690 |
""" Update the state of the backend resources in db.
|
691 |
|
692 |
"""
|
693 |
|
694 |
if not resources: |
695 |
resources = get_physical_resources(backend) |
696 |
|
697 |
backend.mfree = resources['mfree']
|
698 |
backend.mtotal = resources['mtotal']
|
699 |
backend.dfree = resources['dfree']
|
700 |
backend.dtotal = resources['dtotal']
|
701 |
backend.pinst_cnt = resources['pinst_cnt']
|
702 |
backend.ctotal = resources['ctotal']
|
703 |
backend.updated = datetime.now() |
704 |
backend.save() |
705 |
|
706 |
|
707 |
def get_memory_from_instances(backend): |
708 |
""" Get the memory that is used from instances.
|
709 |
|
710 |
Get the used memory of a backend. Note: This is different for
|
711 |
the real memory used, due to kvm's memory de-duplication.
|
712 |
|
713 |
"""
|
714 |
with pooled_rapi_client(backend) as client: |
715 |
instances = client.GetInstances(bulk=True)
|
716 |
mem = 0
|
717 |
for i in instances: |
718 |
mem += i['oper_ram']
|
719 |
return mem
|
720 |
|
721 |
##
|
722 |
## Synchronized operations for reconciliation
|
723 |
##
|
724 |
|
725 |
|
726 |
def create_network_synced(network, backend): |
727 |
result = _create_network_synced(network, backend) |
728 |
if result[0] != 'success': |
729 |
return result
|
730 |
result = connect_network_synced(network, backend) |
731 |
return result
|
732 |
|
733 |
|
734 |
def _create_network_synced(network, backend): |
735 |
with pooled_rapi_client(backend) as client: |
736 |
job = _create_network(network, backend) |
737 |
result = wait_for_job(client, job) |
738 |
return result
|
739 |
|
740 |
|
741 |
def connect_network_synced(network, backend): |
742 |
with pooled_rapi_client(backend) as client: |
743 |
for group in client.GetGroups(): |
744 |
job = client.ConnectNetwork(network.backend_id, group, |
745 |
network.mode, network.link) |
746 |
result = wait_for_job(client, job) |
747 |
if result[0] != 'success': |
748 |
return result
|
749 |
|
750 |
return result
|
751 |
|
752 |
|
753 |
def wait_for_job(client, jobid): |
754 |
result = client.WaitForJobChange(jobid, ['status', 'opresult'], None, None) |
755 |
status = result['job_info'][0] |
756 |
while status not in ['success', 'error', 'cancel']: |
757 |
result = client.WaitForJobChange(jobid, ['status', 'opresult'], |
758 |
[result], None)
|
759 |
status = result['job_info'][0] |
760 |
|
761 |
if status == 'success': |
762 |
return (status, None) |
763 |
else:
|
764 |
error = result['job_info'][1] |
765 |
return (status, error)
|