root / snf-cyclades-app / synnefo / logic / backend.py @ 27cda06b
History | View | Annotate | Download (26.1 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 |
for old_nic, new_nic in zip(old_nics, new_nics): |
184 |
if not (old_nic.ipv4 == new_nic['ipv4'] and |
185 |
old_nic.ipv6 == new_nic['ipv6'] and |
186 |
old_nic.mac == new_nic['mac'] and |
187 |
old_nic.firewall_profile == new_nic['firewall_profile'] and |
188 |
old_nic.index == new_nic['index'] and |
189 |
old_nic.network == new_nic['network']):
|
190 |
return True |
191 |
return False |
192 |
|
193 |
|
194 |
def release_instance_nics(vm): |
195 |
for nic in vm.nics.all(): |
196 |
net = nic.network |
197 |
if nic.ipv4:
|
198 |
net.release_address(nic.ipv4) |
199 |
nic.delete() |
200 |
net.save() |
201 |
|
202 |
|
203 |
@transaction.commit_on_success
|
204 |
def process_network_status(back_network, etime, jobid, opcode, status, logmsg): |
205 |
if status not in [x[0] for x in BACKEND_STATUSES]: |
206 |
raise Network.InvalidBackendMsgError(opcode, status)
|
207 |
|
208 |
back_network.backendjobid = jobid |
209 |
back_network.backendjobstatus = status |
210 |
back_network.backendopcode = opcode |
211 |
back_network.backendlogmsg = logmsg |
212 |
|
213 |
# Notifications of success change the operating state
|
214 |
state_for_success = BackendNetwork.OPER_STATE_FROM_OPCODE.get(opcode, None)
|
215 |
if status == 'success' and state_for_success is not None: |
216 |
back_network.operstate = state_for_success |
217 |
|
218 |
if status in ('canceled', 'error') and opcode == 'OP_NETWORK_ADD': |
219 |
back_network.operstate = 'ERROR'
|
220 |
back_network.backendtime = etime |
221 |
|
222 |
if opcode == 'OP_NETWORK_REMOVE': |
223 |
if status == 'success' or (status == 'error' and |
224 |
back_network.operstate == 'ERROR'):
|
225 |
back_network.operstate = state_for_success |
226 |
back_network.deleted = True
|
227 |
back_network.backendtime = etime |
228 |
|
229 |
if status == 'success': |
230 |
back_network.backendtime = etime |
231 |
back_network.save() |
232 |
# Also you must update the state of the Network!!
|
233 |
update_network_state(back_network.network) |
234 |
|
235 |
|
236 |
def update_network_state(network): |
237 |
"""Update the state of a Network based on BackendNetwork states.
|
238 |
|
239 |
Update the state of a Network based on the operstate of the networks in the
|
240 |
backends that network exists.
|
241 |
|
242 |
The state of the network is:
|
243 |
* ACTIVE: If it is 'ACTIVE' in at least one backend.
|
244 |
* DELETED: If it is is 'DELETED' in all backends that have been created.
|
245 |
|
246 |
This function also releases the resources (MAC prefix or Bridge) and the
|
247 |
quotas for the network.
|
248 |
|
249 |
"""
|
250 |
if network.deleted:
|
251 |
# Network has already been deleted. Just assert that state is also
|
252 |
# DELETED
|
253 |
if not network.state == "DELETED": |
254 |
network.state = "DELETED"
|
255 |
network.save() |
256 |
return
|
257 |
|
258 |
backend_states = [s.operstate for s in network.backend_networks.all()] |
259 |
if not backend_states and network.action != "DESTROY": |
260 |
if network.state != "ACTIVE": |
261 |
network.state = "ACTIVE"
|
262 |
network.save() |
263 |
return
|
264 |
|
265 |
# Network is deleted when all BackendNetworks go to "DELETED" operstate
|
266 |
deleted = reduce(lambda x, y: x == y and "DELETED", backend_states, |
267 |
"DELETED")
|
268 |
|
269 |
# Release the resources on the deletion of the Network
|
270 |
if deleted:
|
271 |
log.info("Network %r deleted. Releasing link %r mac_prefix %r",
|
272 |
network.id, network.mac_prefix, network.link) |
273 |
network.deleted = True
|
274 |
network.state = "DELETED"
|
275 |
if network.mac_prefix:
|
276 |
if network.FLAVORS[network.flavor]["mac_prefix"] == "pool": |
277 |
release_resource(res_type="mac_prefix",
|
278 |
value=network.mac_prefix) |
279 |
if network.link:
|
280 |
if network.FLAVORS[network.flavor]["link"] == "pool": |
281 |
release_resource(res_type="bridge", value=network.link)
|
282 |
|
283 |
# Issue commission
|
284 |
if network.userid:
|
285 |
quotas.issue_and_accept_commission(network, delete=True)
|
286 |
elif not network.public: |
287 |
log.warning("Network %s does not have an owner!", network.id)
|
288 |
network.save() |
289 |
|
290 |
|
291 |
@transaction.commit_on_success
|
292 |
def process_network_modify(back_network, etime, jobid, opcode, status, |
293 |
add_reserved_ips, remove_reserved_ips): |
294 |
assert (opcode == "OP_NETWORK_SET_PARAMS") |
295 |
if status not in [x[0] for x in BACKEND_STATUSES]: |
296 |
raise Network.InvalidBackendMsgError(opcode, status)
|
297 |
|
298 |
back_network.backendjobid = jobid |
299 |
back_network.backendjobstatus = status |
300 |
back_network.opcode = opcode |
301 |
|
302 |
if add_reserved_ips or remove_reserved_ips: |
303 |
net = back_network.network |
304 |
pool = net.get_pool() |
305 |
if add_reserved_ips:
|
306 |
for ip in add_reserved_ips: |
307 |
pool.reserve(ip, external=True)
|
308 |
if remove_reserved_ips:
|
309 |
for ip in remove_reserved_ips: |
310 |
pool.put(ip, external=True)
|
311 |
pool.save() |
312 |
|
313 |
if status == 'success': |
314 |
back_network.backendtime = etime |
315 |
back_network.save() |
316 |
|
317 |
|
318 |
@transaction.commit_on_success
|
319 |
def process_create_progress(vm, etime, progress): |
320 |
|
321 |
percentage = int(progress)
|
322 |
|
323 |
# The percentage may exceed 100%, due to the way
|
324 |
# snf-image:copy-progress tracks bytes read by image handling processes
|
325 |
percentage = 100 if percentage > 100 else percentage |
326 |
if percentage < 0: |
327 |
raise ValueError("Percentage cannot be negative") |
328 |
|
329 |
# FIXME: log a warning here, see #1033
|
330 |
# if last_update > percentage:
|
331 |
# raise ValueError("Build percentage should increase monotonically " \
|
332 |
# "(old = %d, new = %d)" % (last_update, percentage))
|
333 |
|
334 |
# This assumes that no message of type 'ganeti-create-progress' is going to
|
335 |
# arrive once OP_INSTANCE_CREATE has succeeded for a Ganeti instance and
|
336 |
# the instance is STARTED. What if the two messages are processed by two
|
337 |
# separate dispatcher threads, and the 'ganeti-op-status' message for
|
338 |
# successful creation gets processed before the 'ganeti-create-progress'
|
339 |
# message? [vkoukis]
|
340 |
#
|
341 |
#if not vm.operstate == 'BUILD':
|
342 |
# raise VirtualMachine.IllegalState("VM is not in building state")
|
343 |
|
344 |
vm.buildpercentage = percentage |
345 |
vm.backendtime = etime |
346 |
vm.save() |
347 |
|
348 |
|
349 |
def create_instance_diagnostic(vm, message, source, level="DEBUG", etime=None, |
350 |
details=None):
|
351 |
"""
|
352 |
Create virtual machine instance diagnostic entry.
|
353 |
|
354 |
:param vm: VirtualMachine instance to create diagnostic for.
|
355 |
:param message: Diagnostic message.
|
356 |
:param source: Diagnostic source identifier (e.g. image-helper).
|
357 |
:param level: Diagnostic level (`DEBUG`, `INFO`, `WARNING`, `ERROR`).
|
358 |
:param etime: The time the message occured (if available).
|
359 |
:param details: Additional details or debug information.
|
360 |
"""
|
361 |
VirtualMachineDiagnostic.objects.create_for_vm(vm, level, source=source, |
362 |
source_date=etime, |
363 |
message=message, |
364 |
details=details) |
365 |
|
366 |
|
367 |
def create_instance(vm, public_nic, flavor, image): |
368 |
"""`image` is a dictionary which should contain the keys:
|
369 |
'backend_id', 'format' and 'metadata'
|
370 |
|
371 |
metadata value should be a dictionary.
|
372 |
"""
|
373 |
|
374 |
# Handle arguments to CreateInstance() as a dictionary,
|
375 |
# initialize it based on a deployment-specific value.
|
376 |
# This enables the administrator to override deployment-specific
|
377 |
# arguments, such as the disk template to use, name of os provider
|
378 |
# and hypervisor-specific parameters at will (see Synnefo #785, #835).
|
379 |
#
|
380 |
kw = settings.GANETI_CREATEINSTANCE_KWARGS |
381 |
kw['mode'] = 'create' |
382 |
kw['name'] = vm.backend_vm_id
|
383 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
384 |
|
385 |
kw['disk_template'] = flavor.disk_template
|
386 |
kw['disks'] = [{"size": flavor.disk * 1024}] |
387 |
provider = flavor.disk_provider |
388 |
if provider:
|
389 |
kw['disks'][0]['provider'] = provider |
390 |
|
391 |
if provider == 'vlmc': |
392 |
kw['disks'][0]['origin'] = flavor.disk_origin |
393 |
|
394 |
kw['nics'] = [public_nic]
|
395 |
if settings.GANETI_USE_HOTPLUG:
|
396 |
kw['hotplug'] = True |
397 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
398 |
# kw['os'] = settings.GANETI_OS_PROVIDER
|
399 |
kw['ip_check'] = False |
400 |
kw['name_check'] = False |
401 |
|
402 |
# Do not specific a node explicitly, have
|
403 |
# Ganeti use an iallocator instead
|
404 |
#kw['pnode'] = rapi.GetNodes()[0]
|
405 |
|
406 |
kw['dry_run'] = settings.TEST
|
407 |
|
408 |
kw['beparams'] = {
|
409 |
'auto_balance': True, |
410 |
'vcpus': flavor.cpu,
|
411 |
'memory': flavor.ram}
|
412 |
|
413 |
kw['osparams'] = {
|
414 |
'config_url': vm.config_url,
|
415 |
# Store image id and format to Ganeti
|
416 |
'img_id': image['backend_id'], |
417 |
'img_format': image['format']} |
418 |
|
419 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
420 |
# kw['hvparams'] = dict(serial_console=False)
|
421 |
|
422 |
log.debug("Creating instance %s", utils.hide_pass(kw))
|
423 |
with pooled_rapi_client(vm) as client: |
424 |
return client.CreateInstance(**kw)
|
425 |
|
426 |
|
427 |
def delete_instance(vm): |
428 |
with pooled_rapi_client(vm) as client: |
429 |
return client.DeleteInstance(vm.backend_vm_id, dry_run=settings.TEST)
|
430 |
|
431 |
|
432 |
def reboot_instance(vm, reboot_type): |
433 |
assert reboot_type in ('soft', 'hard') |
434 |
with pooled_rapi_client(vm) as client: |
435 |
return client.RebootInstance(vm.backend_vm_id, reboot_type,
|
436 |
dry_run=settings.TEST) |
437 |
|
438 |
|
439 |
def startup_instance(vm): |
440 |
with pooled_rapi_client(vm) as client: |
441 |
return client.StartupInstance(vm.backend_vm_id, dry_run=settings.TEST)
|
442 |
|
443 |
|
444 |
def shutdown_instance(vm): |
445 |
with pooled_rapi_client(vm) as client: |
446 |
return client.ShutdownInstance(vm.backend_vm_id, dry_run=settings.TEST)
|
447 |
|
448 |
|
449 |
def get_instance_console(vm): |
450 |
# RAPI GetInstanceConsole() returns endpoints to the vnc_bind_address,
|
451 |
# which is a cluster-wide setting, either 0.0.0.0 or 127.0.0.1, and pretty
|
452 |
# useless (see #783).
|
453 |
#
|
454 |
# Until this is fixed on the Ganeti side, construct a console info reply
|
455 |
# directly.
|
456 |
#
|
457 |
# WARNING: This assumes that VNC runs on port network_port on
|
458 |
# the instance's primary node, and is probably
|
459 |
# hypervisor-specific.
|
460 |
#
|
461 |
log.debug("Getting console for vm %s", vm)
|
462 |
|
463 |
console = {} |
464 |
console['kind'] = 'vnc' |
465 |
|
466 |
with pooled_rapi_client(vm) as client: |
467 |
i = client.GetInstance(vm.backend_vm_id) |
468 |
|
469 |
if i['hvparams']['serial_console']: |
470 |
raise Exception("hv parameter serial_console cannot be true") |
471 |
console['host'] = i['pnode'] |
472 |
console['port'] = i['network_port'] |
473 |
|
474 |
return console
|
475 |
|
476 |
|
477 |
def get_instance_info(vm): |
478 |
with pooled_rapi_client(vm) as client: |
479 |
return client.GetInstanceInfo(vm.backend_vm_id)
|
480 |
|
481 |
|
482 |
def create_network(network, backend, connect=True): |
483 |
"""Create a network in a Ganeti backend"""
|
484 |
log.debug("Creating network %s in backend %s", network, backend)
|
485 |
|
486 |
job_id = _create_network(network, backend) |
487 |
|
488 |
if connect:
|
489 |
job_ids = connect_network(network, backend, depends=[job_id]) |
490 |
return job_ids
|
491 |
else:
|
492 |
return [job_id]
|
493 |
|
494 |
|
495 |
def _create_network(network, backend): |
496 |
"""Create a network."""
|
497 |
|
498 |
network_type = network.public and 'public' or 'private' |
499 |
|
500 |
tags = network.backend_tag |
501 |
if network.dhcp:
|
502 |
tags.append('nfdhcpd')
|
503 |
|
504 |
if network.public:
|
505 |
conflicts_check = True
|
506 |
else:
|
507 |
conflicts_check = False
|
508 |
|
509 |
try:
|
510 |
bn = BackendNetwork.objects.get(network=network, backend=backend) |
511 |
mac_prefix = bn.mac_prefix |
512 |
except BackendNetwork.DoesNotExist:
|
513 |
raise Exception("BackendNetwork for network '%s' in backend '%s'" |
514 |
" does not exist" % (network.id, backend.id))
|
515 |
|
516 |
with pooled_rapi_client(backend) as client: |
517 |
return client.CreateNetwork(network_name=network.backend_id,
|
518 |
network=network.subnet, |
519 |
network6=network.subnet6, |
520 |
gateway=network.gateway, |
521 |
gateway6=network.gateway6, |
522 |
network_type=network_type, |
523 |
mac_prefix=mac_prefix, |
524 |
conflicts_check=conflicts_check, |
525 |
tags=tags) |
526 |
|
527 |
|
528 |
def connect_network(network, backend, depends=[], group=None): |
529 |
"""Connect a network to nodegroups."""
|
530 |
log.debug("Connecting network %s to backend %s", network, backend)
|
531 |
|
532 |
if network.public:
|
533 |
conflicts_check = True
|
534 |
else:
|
535 |
conflicts_check = False
|
536 |
|
537 |
depends = [[job, ["success", "error", "canceled"]] for job in depends] |
538 |
with pooled_rapi_client(backend) as client: |
539 |
groups = [group] if group is not None else client.GetGroups() |
540 |
job_ids = [] |
541 |
for group in groups: |
542 |
job_id = client.ConnectNetwork(network.backend_id, group, |
543 |
network.mode, network.link, |
544 |
conflicts_check, |
545 |
depends=depends) |
546 |
job_ids.append(job_id) |
547 |
return job_ids
|
548 |
|
549 |
|
550 |
def delete_network(network, backend, disconnect=True): |
551 |
log.debug("Deleting network %s from backend %s", network, backend)
|
552 |
|
553 |
depends = [] |
554 |
if disconnect:
|
555 |
depends = disconnect_network(network, backend) |
556 |
_delete_network(network, backend, depends=depends) |
557 |
|
558 |
|
559 |
def _delete_network(network, backend, depends=[]): |
560 |
depends = [[job, ["success", "error", "canceled"]] for job in depends] |
561 |
with pooled_rapi_client(backend) as client: |
562 |
return client.DeleteNetwork(network.backend_id, depends)
|
563 |
|
564 |
|
565 |
def disconnect_network(network, backend, group=None): |
566 |
log.debug("Disconnecting network %s to backend %s", network, backend)
|
567 |
|
568 |
with pooled_rapi_client(backend) as client: |
569 |
groups = [group] if group is not None else client.GetGroups() |
570 |
job_ids = [] |
571 |
for group in groups: |
572 |
job_id = client.DisconnectNetwork(network.backend_id, group) |
573 |
job_ids.append(job_id) |
574 |
return job_ids
|
575 |
|
576 |
|
577 |
def connect_to_network(vm, network, address=None): |
578 |
backend = vm.backend |
579 |
bnet, created = BackendNetwork.objects.get_or_create(backend=backend, |
580 |
network=network) |
581 |
depend_jobs = [] |
582 |
if bnet.operstate != "ACTIVE": |
583 |
depend_jobs = create_network(network, backend, connect=True)
|
584 |
|
585 |
depends = [[job, ["success", "error", "canceled"]] for job in depend_jobs] |
586 |
|
587 |
nic = {'ip': address, 'network': network.backend_id} |
588 |
|
589 |
log.debug("Connecting vm %s to network %s(%s)", vm, network, address)
|
590 |
|
591 |
with pooled_rapi_client(vm) as client: |
592 |
return client.ModifyInstance(vm.backend_vm_id, nics=[('add', nic)], |
593 |
hotplug=settings.GANETI_USE_HOTPLUG, |
594 |
depends=depends, |
595 |
dry_run=settings.TEST) |
596 |
|
597 |
|
598 |
def disconnect_from_network(vm, nic): |
599 |
op = [('remove', nic.index, {})]
|
600 |
|
601 |
log.debug("Removing nic of VM %s, with index %s", vm, str(nic.index)) |
602 |
|
603 |
with pooled_rapi_client(vm) as client: |
604 |
return client.ModifyInstance(vm.backend_vm_id, nics=op,
|
605 |
hotplug=settings.GANETI_USE_HOTPLUG, |
606 |
dry_run=settings.TEST) |
607 |
|
608 |
|
609 |
def set_firewall_profile(vm, profile): |
610 |
try:
|
611 |
tag = _firewall_tags[profile] |
612 |
except KeyError: |
613 |
raise ValueError("Unsopported Firewall Profile: %s" % profile) |
614 |
|
615 |
log.debug("Setting tag of VM %s to %s", vm, profile)
|
616 |
|
617 |
with pooled_rapi_client(vm) as client: |
618 |
# Delete all firewall tags
|
619 |
for t in _firewall_tags.values(): |
620 |
client.DeleteInstanceTags(vm.backend_vm_id, [t], |
621 |
dry_run=settings.TEST) |
622 |
|
623 |
client.AddInstanceTags(vm.backend_vm_id, [tag], dry_run=settings.TEST) |
624 |
|
625 |
# XXX NOP ModifyInstance call to force process_net_status to run
|
626 |
# on the dispatcher
|
627 |
os_name = settings.GANETI_CREATEINSTANCE_KWARGS['os']
|
628 |
client.ModifyInstance(vm.backend_vm_id, |
629 |
os_name=os_name) |
630 |
|
631 |
|
632 |
def get_ganeti_instances(backend=None, bulk=False): |
633 |
instances = [] |
634 |
for backend in get_backends(backend): |
635 |
with pooled_rapi_client(backend) as client: |
636 |
instances.append(client.GetInstances(bulk=bulk)) |
637 |
|
638 |
return reduce(list.__add__, instances, []) |
639 |
|
640 |
|
641 |
def get_ganeti_nodes(backend=None, bulk=False): |
642 |
nodes = [] |
643 |
for backend in get_backends(backend): |
644 |
with pooled_rapi_client(backend) as client: |
645 |
nodes.append(client.GetNodes(bulk=bulk)) |
646 |
|
647 |
return reduce(list.__add__, nodes, []) |
648 |
|
649 |
|
650 |
def get_ganeti_jobs(backend=None, bulk=False): |
651 |
jobs = [] |
652 |
for backend in get_backends(backend): |
653 |
with pooled_rapi_client(backend) as client: |
654 |
jobs.append(client.GetJobs(bulk=bulk)) |
655 |
return reduce(list.__add__, jobs, []) |
656 |
|
657 |
##
|
658 |
##
|
659 |
##
|
660 |
|
661 |
|
662 |
def get_backends(backend=None): |
663 |
if backend:
|
664 |
if backend.offline:
|
665 |
return []
|
666 |
return [backend]
|
667 |
return Backend.objects.filter(offline=False) |
668 |
|
669 |
|
670 |
def get_physical_resources(backend): |
671 |
""" Get the physical resources of a backend.
|
672 |
|
673 |
Get the resources of a backend as reported by the backend (not the db).
|
674 |
|
675 |
"""
|
676 |
nodes = get_ganeti_nodes(backend, bulk=True)
|
677 |
attr = ['mfree', 'mtotal', 'dfree', 'dtotal', 'pinst_cnt', 'ctotal'] |
678 |
res = {} |
679 |
for a in attr: |
680 |
res[a] = 0
|
681 |
for n in nodes: |
682 |
# Filter out drained, offline and not vm_capable nodes since they will
|
683 |
# not take part in the vm allocation process
|
684 |
can_host_vms = n['vm_capable'] and not (n['drained'] or n['offline']) |
685 |
if can_host_vms and n['cnodes']: |
686 |
for a in attr: |
687 |
res[a] += int(n[a])
|
688 |
return res
|
689 |
|
690 |
|
691 |
def update_resources(backend, resources=None): |
692 |
""" Update the state of the backend resources in db.
|
693 |
|
694 |
"""
|
695 |
|
696 |
if not resources: |
697 |
resources = get_physical_resources(backend) |
698 |
|
699 |
backend.mfree = resources['mfree']
|
700 |
backend.mtotal = resources['mtotal']
|
701 |
backend.dfree = resources['dfree']
|
702 |
backend.dtotal = resources['dtotal']
|
703 |
backend.pinst_cnt = resources['pinst_cnt']
|
704 |
backend.ctotal = resources['ctotal']
|
705 |
backend.updated = datetime.now() |
706 |
backend.save() |
707 |
|
708 |
|
709 |
def get_memory_from_instances(backend): |
710 |
""" Get the memory that is used from instances.
|
711 |
|
712 |
Get the used memory of a backend. Note: This is different for
|
713 |
the real memory used, due to kvm's memory de-duplication.
|
714 |
|
715 |
"""
|
716 |
with pooled_rapi_client(backend) as client: |
717 |
instances = client.GetInstances(bulk=True)
|
718 |
mem = 0
|
719 |
for i in instances: |
720 |
mem += i['oper_ram']
|
721 |
return mem
|
722 |
|
723 |
##
|
724 |
## Synchronized operations for reconciliation
|
725 |
##
|
726 |
|
727 |
|
728 |
def create_network_synced(network, backend): |
729 |
result = _create_network_synced(network, backend) |
730 |
if result[0] != 'success': |
731 |
return result
|
732 |
result = connect_network_synced(network, backend) |
733 |
return result
|
734 |
|
735 |
|
736 |
def _create_network_synced(network, backend): |
737 |
with pooled_rapi_client(backend) as client: |
738 |
job = _create_network(network, backend) |
739 |
result = wait_for_job(client, job) |
740 |
return result
|
741 |
|
742 |
|
743 |
def connect_network_synced(network, backend): |
744 |
with pooled_rapi_client(backend) as client: |
745 |
for group in client.GetGroups(): |
746 |
job = client.ConnectNetwork(network.backend_id, group, |
747 |
network.mode, network.link) |
748 |
result = wait_for_job(client, job) |
749 |
if result[0] != 'success': |
750 |
return result
|
751 |
|
752 |
return result
|
753 |
|
754 |
|
755 |
def wait_for_job(client, jobid): |
756 |
result = client.WaitForJobChange(jobid, ['status', 'opresult'], None, None) |
757 |
status = result['job_info'][0] |
758 |
while status not in ['success', 'error', 'cancel']: |
759 |
result = client.WaitForJobChange(jobid, ['status', 'opresult'], |
760 |
[result], None)
|
761 |
status = result['job_info'][0] |
762 |
|
763 |
if status == 'success': |
764 |
return (status, None) |
765 |
else:
|
766 |
error = result['job_info'][1] |
767 |
return (status, error)
|