root / snf-cyclades-app / synnefo / logic / backend.py @ 924d8085
History | View | Annotate | Download (14.3 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 logging import getLogger |
37 |
|
38 |
from django.conf import settings |
39 |
from django.db import transaction |
40 |
|
41 |
from synnefo.db.models import (VirtualMachine, Network, NetworkLink) |
42 |
from synnefo.logic import utils |
43 |
from synnefo.util.rapi import GanetiRapiClient |
44 |
|
45 |
|
46 |
log = getLogger('synnefo.logic')
|
47 |
|
48 |
rapi = GanetiRapiClient(*settings.GANETI_CLUSTER_INFO) |
49 |
|
50 |
_firewall_tags = { |
51 |
'ENABLED': settings.GANETI_FIREWALL_ENABLED_TAG,
|
52 |
'DISABLED': settings.GANETI_FIREWALL_DISABLED_TAG,
|
53 |
'PROTECTED': settings.GANETI_FIREWALL_PROTECTED_TAG}
|
54 |
|
55 |
_reverse_tags = dict((v.split(':')[3], k) for k, v in _firewall_tags.items()) |
56 |
|
57 |
|
58 |
def create_client(hostname, port=5080, username=None, password=None): |
59 |
return GanetiRapiClient(hostname=hostname,
|
60 |
port=port, |
61 |
username=username, |
62 |
password=password) |
63 |
|
64 |
@transaction.commit_on_success
|
65 |
def process_op_status(vm, etime, jobid, opcode, status, logmsg): |
66 |
"""Process a job progress notification from the backend
|
67 |
|
68 |
Process an incoming message from the backend (currently Ganeti).
|
69 |
Job notifications with a terminating status (sucess, error, or canceled),
|
70 |
also update the operating state of the VM.
|
71 |
|
72 |
"""
|
73 |
# See #1492, #1031, #1111 why this line has been removed
|
74 |
#if (opcode not in [x[0] for x in VirtualMachine.BACKEND_OPCODES] or
|
75 |
if status not in [x[0] for x in VirtualMachine.BACKEND_STATUSES]: |
76 |
raise VirtualMachine.InvalidBackendMsgError(opcode, status)
|
77 |
|
78 |
vm.backendjobid = jobid |
79 |
vm.backendjobstatus = status |
80 |
vm.backendopcode = opcode |
81 |
vm.backendlogmsg = logmsg |
82 |
|
83 |
# Notifications of success change the operating state
|
84 |
state_for_success = VirtualMachine.OPER_STATE_FROM_OPCODE.get(opcode, None)
|
85 |
if status == 'success' and state_for_success is not None: |
86 |
utils.update_state(vm, state_for_success) |
87 |
# Set the deleted flag explicitly, cater for admin-initiated removals
|
88 |
if opcode == 'OP_INSTANCE_REMOVE': |
89 |
vm.deleted = True
|
90 |
vm.nics.all().delete() |
91 |
|
92 |
# Special case: if OP_INSTANCE_CREATE fails --> ERROR
|
93 |
if status in ('canceled', 'error') and opcode == 'OP_INSTANCE_CREATE': |
94 |
utils.update_state(vm, 'ERROR')
|
95 |
|
96 |
# Special case: OP_INSTANCE_REMOVE fails for machines in ERROR,
|
97 |
# when no instance exists at the Ganeti backend.
|
98 |
# See ticket #799 for all the details.
|
99 |
#
|
100 |
if (status == 'error' and opcode == 'OP_INSTANCE_REMOVE' and |
101 |
vm.operstate == 'ERROR'):
|
102 |
vm.deleted = True
|
103 |
vm.nics.all().delete() |
104 |
|
105 |
vm.backendtime = etime |
106 |
# Any other notification of failure leaves the operating state unchanged
|
107 |
|
108 |
vm.save() |
109 |
|
110 |
|
111 |
@transaction.commit_on_success
|
112 |
def process_net_status(vm, etime, nics): |
113 |
"""Process a net status notification from the backend
|
114 |
|
115 |
Process an incoming message from the Ganeti backend,
|
116 |
detailing the NIC configuration of a VM instance.
|
117 |
|
118 |
Update the state of the VM in the DB accordingly.
|
119 |
"""
|
120 |
|
121 |
vm.nics.all().delete() |
122 |
for i, nic in enumerate(nics): |
123 |
if i == 0: |
124 |
net = Network.objects.get(public=True)
|
125 |
else:
|
126 |
try:
|
127 |
link = NetworkLink.objects.get(name=nic['link'])
|
128 |
except NetworkLink.DoesNotExist:
|
129 |
# Cannot find an instance of NetworkLink for
|
130 |
# the link attribute specified in the notification
|
131 |
raise NetworkLink.DoesNotExist("Cannot find a NetworkLink " |
132 |
"object for link='%s'" % nic['link']) |
133 |
net = link.network |
134 |
if net is None: |
135 |
raise Network.DoesNotExist("NetworkLink for link='%s' not " |
136 |
"associated with an existing Network instance." %
|
137 |
nic['link'])
|
138 |
|
139 |
firewall = nic.get('firewall', '') |
140 |
firewall_profile = _reverse_tags.get(firewall, '')
|
141 |
if not firewall_profile and net.public: |
142 |
firewall_profile = settings.DEFAULT_FIREWALL_PROFILE |
143 |
|
144 |
vm.nics.create( |
145 |
network=net, |
146 |
index=i, |
147 |
mac=nic.get('mac', ''), |
148 |
ipv4=nic.get('ip', ''), |
149 |
ipv6=nic.get('ipv6', ''), |
150 |
firewall_profile=firewall_profile) |
151 |
|
152 |
# network nics modified, update network object
|
153 |
net.save() |
154 |
|
155 |
vm.backendtime = etime |
156 |
vm.save() |
157 |
|
158 |
|
159 |
@transaction.commit_on_success
|
160 |
def process_create_progress(vm, etime, rprogress, wprogress): |
161 |
|
162 |
# XXX: This only uses the read progress for now.
|
163 |
# Explore whether it would make sense to use the value of wprogress
|
164 |
# somewhere.
|
165 |
percentage = int(rprogress)
|
166 |
|
167 |
# The percentage may exceed 100%, due to the way
|
168 |
# snf-progress-monitor tracks bytes read by image handling processes
|
169 |
percentage = 100 if percentage > 100 else percentage |
170 |
if percentage < 0: |
171 |
raise ValueError("Percentage cannot be negative") |
172 |
|
173 |
# FIXME: log a warning here, see #1033
|
174 |
# if last_update > percentage:
|
175 |
# raise ValueError("Build percentage should increase monotonically " \
|
176 |
# "(old = %d, new = %d)" % (last_update, percentage))
|
177 |
|
178 |
# This assumes that no message of type 'ganeti-create-progress' is going to
|
179 |
# arrive once OP_INSTANCE_CREATE has succeeded for a Ganeti instance and
|
180 |
# the instance is STARTED. What if the two messages are processed by two
|
181 |
# separate dispatcher threads, and the 'ganeti-op-status' message for
|
182 |
# successful creation gets processed before the 'ganeti-create-progress'
|
183 |
# message? [vkoukis]
|
184 |
#
|
185 |
#if not vm.operstate == 'BUILD':
|
186 |
# raise VirtualMachine.IllegalState("VM is not in building state")
|
187 |
|
188 |
vm.buildpercentage = percentage |
189 |
vm.backendtime = etime |
190 |
vm.save() |
191 |
|
192 |
|
193 |
def start_action(vm, action): |
194 |
"""Update the state of a VM when a new action is initiated."""
|
195 |
if not action in [x[0] for x in VirtualMachine.ACTIONS]: |
196 |
raise VirtualMachine.InvalidActionError(action)
|
197 |
|
198 |
# No actions to deleted and no actions beside destroy to suspended VMs
|
199 |
if vm.deleted:
|
200 |
raise VirtualMachine.DeletedError
|
201 |
|
202 |
# No actions to machines being built. They may be destroyed, however.
|
203 |
if vm.operstate == 'BUILD' and action != 'DESTROY': |
204 |
raise VirtualMachine.BuildingError
|
205 |
|
206 |
vm.action = action |
207 |
vm.backendjobid = None
|
208 |
vm.backendopcode = None
|
209 |
vm.backendjobstatus = None
|
210 |
vm.backendlogmsg = None
|
211 |
|
212 |
# Update the relevant flags if the VM is being suspended or destroyed.
|
213 |
# Do not set the deleted flag here, see ticket #721.
|
214 |
#
|
215 |
# The deleted flag is set asynchronously, when an OP_INSTANCE_REMOVE
|
216 |
# completes successfully. Hence, a server may be visible for some time
|
217 |
# after a DELETE /servers/id returns HTTP 204.
|
218 |
#
|
219 |
if action == "DESTROY": |
220 |
# vm.deleted = True
|
221 |
pass
|
222 |
elif action == "SUSPEND": |
223 |
vm.suspended = True
|
224 |
elif action == "START": |
225 |
vm.suspended = False
|
226 |
vm.save() |
227 |
|
228 |
|
229 |
def create_instance(vm, flavor, image, password, personality): |
230 |
"""`image` is a dictionary which should contain the keys:
|
231 |
'backend_id', 'format' and 'metadata'
|
232 |
|
233 |
metadata value should be a dictionary.
|
234 |
"""
|
235 |
nic = {'ip': 'pool', 'network': settings.GANETI_PUBLIC_NETWORK} |
236 |
|
237 |
if settings.IGNORE_FLAVOR_DISK_SIZES:
|
238 |
if image['backend_id'].find("windows") >= 0: |
239 |
sz = 14000
|
240 |
else:
|
241 |
sz = 4000
|
242 |
else:
|
243 |
sz = flavor.disk * 1024
|
244 |
|
245 |
# Handle arguments to CreateInstance() as a dictionary,
|
246 |
# initialize it based on a deployment-specific value.
|
247 |
# This enables the administrator to override deployment-specific
|
248 |
# arguments, such as the disk template to use, name of os provider
|
249 |
# and hypervisor-specific parameters at will (see Synnefo #785, #835).
|
250 |
#
|
251 |
kw = settings.GANETI_CREATEINSTANCE_KWARGS |
252 |
kw['mode'] = 'create' |
253 |
kw['name'] = vm.backend_vm_id
|
254 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
255 |
kw['disk_template'] = flavor.disk_template
|
256 |
kw['disks'] = [{"size": sz}] |
257 |
kw['nics'] = [nic]
|
258 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
259 |
# kw['os'] = settings.GANETI_OS_PROVIDER
|
260 |
kw['ip_check'] = False |
261 |
kw['name_check'] = False |
262 |
# Do not specific a node explicitly, have
|
263 |
# Ganeti use an iallocator instead
|
264 |
#
|
265 |
# kw['pnode']=rapi.GetNodes()[0]
|
266 |
kw['dry_run'] = settings.TEST
|
267 |
|
268 |
kw['beparams'] = {
|
269 |
'auto_balance': True, |
270 |
'vcpus': flavor.cpu,
|
271 |
'memory': flavor.ram}
|
272 |
|
273 |
kw['osparams'] = {
|
274 |
'img_id': image['backend_id'], |
275 |
'img_passwd': password,
|
276 |
'img_format': image['format']} |
277 |
if personality:
|
278 |
kw['osparams']['img_personality'] = json.dumps(personality) |
279 |
|
280 |
kw['osparams']['img_properties'] = json.dumps(image['metadata']) |
281 |
|
282 |
# Defined in settings.GANETI_CREATEINSTANCE_KWARGS
|
283 |
# kw['hvparams'] = dict(serial_console=False)
|
284 |
|
285 |
return rapi.CreateInstance(**kw)
|
286 |
|
287 |
|
288 |
def delete_instance(vm): |
289 |
start_action(vm, 'DESTROY')
|
290 |
rapi.DeleteInstance(vm.backend_vm_id, dry_run=settings.TEST) |
291 |
|
292 |
|
293 |
def reboot_instance(vm, reboot_type): |
294 |
assert reboot_type in ('soft', 'hard') |
295 |
rapi.RebootInstance(vm.backend_vm_id, reboot_type, dry_run=settings.TEST) |
296 |
log.info('Rebooting instance %s', vm.backend_vm_id)
|
297 |
|
298 |
|
299 |
def startup_instance(vm): |
300 |
start_action(vm, 'START')
|
301 |
rapi.StartupInstance(vm.backend_vm_id, dry_run=settings.TEST) |
302 |
|
303 |
|
304 |
def shutdown_instance(vm): |
305 |
start_action(vm, 'STOP')
|
306 |
rapi.ShutdownInstance(vm.backend_vm_id, dry_run=settings.TEST) |
307 |
|
308 |
|
309 |
def get_instance_console(vm): |
310 |
# RAPI GetInstanceConsole() returns endpoints to the vnc_bind_address,
|
311 |
# which is a cluster-wide setting, either 0.0.0.0 or 127.0.0.1, and pretty
|
312 |
# useless (see #783).
|
313 |
#
|
314 |
# Until this is fixed on the Ganeti side, construct a console info reply
|
315 |
# directly.
|
316 |
#
|
317 |
# WARNING: This assumes that VNC runs on port network_port on
|
318 |
# the instance's primary node, and is probably
|
319 |
# hypervisor-specific.
|
320 |
#
|
321 |
console = {} |
322 |
console['kind'] = 'vnc' |
323 |
i = rapi.GetInstance(vm.backend_vm_id) |
324 |
if i['hvparams']['serial_console']: |
325 |
raise Exception("hv parameter serial_console cannot be true") |
326 |
console['host'] = i['pnode'] |
327 |
console['port'] = i['network_port'] |
328 |
|
329 |
return console
|
330 |
# return rapi.GetInstanceConsole(vm.backend_vm_id)
|
331 |
|
332 |
|
333 |
def request_status_update(vm): |
334 |
return rapi.GetInstanceInfo(vm.backend_vm_id)
|
335 |
|
336 |
|
337 |
def get_job_status(jobid): |
338 |
return rapi.GetJobStatus(jobid)
|
339 |
|
340 |
|
341 |
def update_status(vm, status): |
342 |
utils.update_state(vm, status) |
343 |
|
344 |
|
345 |
def create_network_link(): |
346 |
try:
|
347 |
last = NetworkLink.objects.order_by('-index')[0] |
348 |
index = last.index + 1
|
349 |
except IndexError: |
350 |
index = 1
|
351 |
|
352 |
if index <= settings.GANETI_MAX_LINK_NUMBER:
|
353 |
name = '%s%d' % (settings.GANETI_LINK_PREFIX, index)
|
354 |
return NetworkLink.objects.create(index=index, name=name,
|
355 |
available=True)
|
356 |
return None # All link slots are filled |
357 |
|
358 |
|
359 |
@transaction.commit_on_success
|
360 |
def create_network(name, user_id): |
361 |
try:
|
362 |
link = NetworkLink.objects.filter(available=True)[0] |
363 |
except IndexError: |
364 |
link = create_network_link() |
365 |
if not link: |
366 |
raise NetworkLink.NotAvailable
|
367 |
|
368 |
network = Network.objects.create( |
369 |
name=name, |
370 |
userid=user_id, |
371 |
state='ACTIVE',
|
372 |
link=link) |
373 |
|
374 |
link.network = network |
375 |
link.available = False
|
376 |
link.save() |
377 |
|
378 |
return network
|
379 |
|
380 |
|
381 |
@transaction.commit_on_success
|
382 |
def delete_network(net): |
383 |
link = net.link |
384 |
if link.name != settings.GANETI_NULL_LINK:
|
385 |
link.available = True
|
386 |
link.network = None
|
387 |
link.save() |
388 |
|
389 |
for vm in net.machines.all(): |
390 |
disconnect_from_network(vm, net) |
391 |
vm.save() |
392 |
net.state = 'DELETED'
|
393 |
net.save() |
394 |
|
395 |
|
396 |
def connect_to_network(vm, net): |
397 |
nic = {'mode': 'bridged', 'link': net.link.name} |
398 |
rapi.ModifyInstance(vm.backend_vm_id, nics=[('add', -1, nic)], |
399 |
hotplug=True, dry_run=settings.TEST)
|
400 |
|
401 |
|
402 |
def disconnect_from_network(vm, net): |
403 |
nics = vm.nics.filter(network__public=False).order_by('index') |
404 |
ops = [('remove', nic.index, {}) for nic in nics if nic.network == net] |
405 |
if not ops: # Vm not connected to network |
406 |
return
|
407 |
rapi.ModifyInstance(vm.backend_vm_id, nics=ops[::-1],
|
408 |
hotplug=True, dry_run=settings.TEST)
|
409 |
|
410 |
|
411 |
def set_firewall_profile(vm, profile): |
412 |
try:
|
413 |
tag = _firewall_tags[profile] |
414 |
except KeyError: |
415 |
raise ValueError("Unsopported Firewall Profile: %s" % profile) |
416 |
|
417 |
# Delete all firewall tags
|
418 |
for t in _firewall_tags.values(): |
419 |
rapi.DeleteInstanceTags(vm.backend_vm_id, [t], dry_run=settings.TEST) |
420 |
|
421 |
rapi.AddInstanceTags(vm.backend_vm_id, [tag], dry_run=settings.TEST) |
422 |
|
423 |
# XXX NOP ModifyInstance call to force process_net_status to run
|
424 |
# on the dispatcher
|
425 |
rapi.ModifyInstance(vm.backend_vm_id, |
426 |
os_name=settings.GANETI_CREATEINSTANCE_KWARGS['os'])
|
427 |
|
428 |
|
429 |
def get_ganeti_instances(): |
430 |
return rapi.GetInstances()
|
431 |
|
432 |
|
433 |
def get_ganeti_nodes(): |
434 |
return rapi.GetNodes()
|
435 |
|
436 |
|
437 |
def get_ganeti_jobs(): |
438 |
return rapi.GetJobs()
|