root / logic / backend.py @ 61868190
History | View | Annotate | Download (10 kB)
1 |
# Copyright 2011 GRNET S.A. All rights reserved.
|
---|---|
2 |
|
3 |
#
|
4 |
# Redistribution and use in source and binary forms, with or
|
5 |
# without modification, are permitted provided that the following
|
6 |
# conditions are met:
|
7 |
#
|
8 |
# 1. Redistributions of source code must retain the above
|
9 |
# copyright notice, this list of conditions and the following
|
10 |
# disclaimer.
|
11 |
#
|
12 |
# 2. Redistributions in binary form must reproduce the above
|
13 |
# copyright notice, this list of conditions and the following
|
14 |
# disclaimer in the documentation and/or other materials
|
15 |
# provided with the distribution.
|
16 |
#
|
17 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
18 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
19 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
20 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
21 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
22 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
23 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
24 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
25 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
26 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
27 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
28 |
# POSSIBILITY OF SUCH DAMAGE.
|
29 |
#
|
30 |
# The views and conclusions contained in the software and
|
31 |
# documentation are those of the authors and should not be
|
32 |
# interpreted as representing official policies, either expressed
|
33 |
# or implied, of GRNET S.A.
|
34 |
|
35 |
from django.conf import settings |
36 |
from django.db import transaction |
37 |
|
38 |
from synnefo.db.models import (VirtualMachine, Network, NetworkInterface, |
39 |
NetworkLink) |
40 |
from synnefo.logic import utils |
41 |
from synnefo.util.rapi import GanetiRapiClient |
42 |
|
43 |
|
44 |
rapi = GanetiRapiClient(*settings.GANETI_CLUSTER_INFO) |
45 |
|
46 |
_firewall_tags = { |
47 |
'ENABLED': settings.GANETI_FIREWALL_ENABLED_TAG,
|
48 |
'DISABLED': settings.GANETI_FIREWALL_DISABLED_TAG,
|
49 |
'PROTECTED': settings.GANETI_FIREWALL_PROTECTED_TAG}
|
50 |
|
51 |
_reverse_tags = dict((v.split(':')[3], k) for k, v in _firewall_tags.items()) |
52 |
|
53 |
|
54 |
def process_op_status(vm, jobid, opcode, status, logmsg): |
55 |
"""Process a job progress notification from the backend
|
56 |
|
57 |
Process an incoming message from the backend (currently Ganeti).
|
58 |
Job notifications with a terminating status (sucess, error, or canceled),
|
59 |
also update the operating state of the VM.
|
60 |
|
61 |
"""
|
62 |
if (opcode not in [x[0] for x in VirtualMachine.BACKEND_OPCODES] or |
63 |
status not in [x[0] for x in VirtualMachine.BACKEND_STATUSES]): |
64 |
raise VirtualMachine.InvalidBackendMsgError(opcode, status)
|
65 |
|
66 |
vm.backendjobid = jobid |
67 |
vm.backendjobstatus = status |
68 |
vm.backendopcode = opcode |
69 |
vm.backendlogmsg = logmsg |
70 |
|
71 |
# Notifications of success change the operating state
|
72 |
if status == 'success' and VirtualMachine.OPER_STATE_FROM_OPCODE[opcode] is not None: |
73 |
utils.update_state(vm, VirtualMachine.OPER_STATE_FROM_OPCODE[opcode]) |
74 |
# Set the deleted flag explicitly, to cater for admin-initiated removals
|
75 |
if opcode == 'OP_INSTANCE_REMOVE': |
76 |
vm.deleted = True
|
77 |
|
78 |
# Special case: if OP_INSTANCE_CREATE fails --> ERROR
|
79 |
if status in ('canceled', 'error') and opcode == 'OP_INSTANCE_CREATE': |
80 |
utils.update_state(vm, 'ERROR')
|
81 |
# Any other notification of failure leaves the operating state unchanged
|
82 |
|
83 |
vm.save() |
84 |
|
85 |
|
86 |
@transaction.commit_on_success
|
87 |
def process_net_status(vm, nics): |
88 |
"""Process a net status notification from the backend
|
89 |
|
90 |
Process an incoming message from the Ganeti backend,
|
91 |
detailing the NIC configuration of a VM instance.
|
92 |
|
93 |
Update the state of the VM in the DB accordingly.
|
94 |
"""
|
95 |
|
96 |
vm.nics.all().delete() |
97 |
for i, nic in enumerate(nics): |
98 |
if i == 0: |
99 |
net = Network.objects.get(public=True)
|
100 |
else:
|
101 |
try:
|
102 |
link = NetworkLink.objects.get(name=nic['link'])
|
103 |
except NetworkLink.DoesNotExist:
|
104 |
# Cannot find an instance of NetworkLink for
|
105 |
# the link attribute specified in the notification
|
106 |
raise NetworkLink.DoesNotExist("Cannot find a NetworkLink " |
107 |
"object for link='%s'" % nic['link']) |
108 |
net = link.network |
109 |
if net is None: |
110 |
raise Network.DoesNotExist("NetworkLink for link='%s' not " |
111 |
"associated with an existing Network instance." %
|
112 |
nic['link'])
|
113 |
|
114 |
firewall = nic.get('firewall', '') |
115 |
firewall_profile = _reverse_tags.get(firewall, '')
|
116 |
if not firewall_profile and net.public: |
117 |
firewall_profile = settings.DEFAULT_FIREWALL_PROFILE |
118 |
|
119 |
vm.nics.create( |
120 |
network=net, |
121 |
index=i, |
122 |
mac=nic.get('mac', ''), |
123 |
ipv4=nic.get('ip', ''), |
124 |
ipv6=nic.get('ipv6',''), |
125 |
firewall_profile=firewall_profile) |
126 |
vm.save() |
127 |
|
128 |
|
129 |
def start_action(vm, action): |
130 |
"""Update the state of a VM when a new action is initiated."""
|
131 |
if not action in [x[0] for x in VirtualMachine.ACTIONS]: |
132 |
raise VirtualMachine.InvalidActionError(action)
|
133 |
|
134 |
# No actions to deleted and no actions beside destroy to suspended VMs
|
135 |
if vm.deleted:
|
136 |
raise VirtualMachine.DeletedError
|
137 |
|
138 |
# No actions to machines being built. They may be destroyed, however.
|
139 |
if vm.operstate == 'BUILD' and action != 'DESTROY': |
140 |
raise VirtualMachine.BuildingError
|
141 |
|
142 |
vm.action = action |
143 |
vm.backendjobid = None
|
144 |
vm.backendopcode = None
|
145 |
vm.backendjobstatus = None
|
146 |
vm.backendlogmsg = None
|
147 |
|
148 |
# Update the relevant flags if the VM is being suspended or destroyed
|
149 |
if action == "DESTROY": |
150 |
vm.deleted = True
|
151 |
elif action == "SUSPEND": |
152 |
vm.suspended = True
|
153 |
elif action == "START": |
154 |
vm.suspended = False
|
155 |
vm.save() |
156 |
|
157 |
|
158 |
def create_instance(vm, flavor, image, password): |
159 |
|
160 |
nic = {'ip': 'pool', 'mode': 'routed', 'link': settings.GANETI_PUBLIC_LINK} |
161 |
|
162 |
if settings.IGNORE_FLAVOR_DISK_SIZES:
|
163 |
if image.backend_id.find("windows") >= 0: |
164 |
sz = 14000
|
165 |
else:
|
166 |
sz = 4000
|
167 |
else:
|
168 |
sz = flavor.disk * 1024
|
169 |
|
170 |
return rapi.CreateInstance(
|
171 |
mode='create',
|
172 |
name=vm.backend_id, |
173 |
disk_template='plain',
|
174 |
disks=[{"size": sz}], #FIXME: Always ask for a 4GB disk for now |
175 |
nics=[nic], |
176 |
os=settings.GANETI_OS_PROVIDER, |
177 |
ip_check=False,
|
178 |
name_check=False,
|
179 |
# Do not specific a node explicitly, have
|
180 |
# Ganeti use an iallocator instead
|
181 |
#
|
182 |
# pnode=rapi.GetNodes()[0],
|
183 |
dry_run=settings.TEST, |
184 |
beparams=dict(auto_balance=True, vcpus=flavor.cpu, memory=flavor.ram), |
185 |
osparams=dict(img_id=image.backend_id, img_passwd=password,
|
186 |
img_format=image.format)) |
187 |
|
188 |
|
189 |
def delete_instance(vm): |
190 |
start_action(vm, 'DESTROY')
|
191 |
rapi.DeleteInstance(vm.backend_id, dry_run=settings.TEST) |
192 |
vm.nics.all().delete() |
193 |
|
194 |
|
195 |
def reboot_instance(vm, reboot_type): |
196 |
assert reboot_type in ('soft', 'hard') |
197 |
rapi.RebootInstance(vm.backend_id, reboot_type, dry_run=settings.TEST) |
198 |
|
199 |
|
200 |
def startup_instance(vm): |
201 |
start_action(vm, 'START')
|
202 |
rapi.StartupInstance(vm.backend_id, dry_run=settings.TEST) |
203 |
|
204 |
|
205 |
def shutdown_instance(vm): |
206 |
start_action(vm, 'STOP')
|
207 |
rapi.ShutdownInstance(vm.backend_id, dry_run=settings.TEST) |
208 |
|
209 |
|
210 |
def get_instance_console(vm): |
211 |
return rapi.GetInstanceConsole(vm.backend_id)
|
212 |
|
213 |
|
214 |
def request_status_update(vm): |
215 |
return rapi.GetInstanceInfo(vm.backend_id)
|
216 |
|
217 |
|
218 |
def get_job_status(jobid): |
219 |
return rapi.GetJobStatus(jobid)
|
220 |
|
221 |
|
222 |
def update_status(vm, status): |
223 |
utils.update_state(vm, status) |
224 |
|
225 |
def create_network_link(): |
226 |
try:
|
227 |
last = NetworkLink.objects.order_by('-index')[0] |
228 |
index = last.index + 1
|
229 |
except IndexError: |
230 |
index = 1
|
231 |
|
232 |
if index <= settings.GANETI_MAX_LINK_NUMBER:
|
233 |
name = '%s%d' % (settings.GANETI_LINK_PREFIX, index)
|
234 |
return NetworkLink.objects.create(index=index, name=name,
|
235 |
available=True)
|
236 |
return None # All link slots are filled |
237 |
|
238 |
@transaction.commit_on_success
|
239 |
def create_network(name, owner): |
240 |
try:
|
241 |
link = NetworkLink.objects.filter(available=True)[0] |
242 |
except IndexError: |
243 |
link = create_network_link() |
244 |
if not link: |
245 |
return None |
246 |
|
247 |
network = Network.objects.create( |
248 |
name=name, |
249 |
owner=owner, |
250 |
state='ACTIVE',
|
251 |
link=link) |
252 |
|
253 |
link.network = network |
254 |
link.available = False
|
255 |
link.save() |
256 |
|
257 |
return network
|
258 |
|
259 |
@transaction.commit_on_success
|
260 |
def delete_network(net): |
261 |
link = net.link |
262 |
if link.name != settings.GANETI_NULL_LINK:
|
263 |
link.available = True
|
264 |
link.network = None
|
265 |
link.save() |
266 |
|
267 |
for vm in net.machines.all(): |
268 |
disconnect_from_network(vm, net) |
269 |
vm.save() |
270 |
net.state = 'DELETED'
|
271 |
net.save() |
272 |
|
273 |
def connect_to_network(vm, net): |
274 |
nic = {'mode': 'bridged', 'link': net.link.name} |
275 |
rapi.ModifyInstance(vm.backend_id, |
276 |
nics=[('add', nic)],
|
277 |
dry_run=settings.TEST) |
278 |
|
279 |
def disconnect_from_network(vm, net): |
280 |
nics = vm.nics.filter(network__public=False).order_by('index') |
281 |
new_nics = [nic for nic in nics if nic.network != net] |
282 |
if new_nics == nics:
|
283 |
return # Nothing to remove |
284 |
ops = [('remove', {})]
|
285 |
for i, nic in enumerate(new_nics): |
286 |
ops.append((i + 1, {
|
287 |
'mode': 'bridged', |
288 |
'link': nic.network.link.name}))
|
289 |
rapi.ModifyInstance(vm.backend_id, nics=ops, dry_run=settings.TEST) |
290 |
|
291 |
def set_firewall_profile(vm, profile): |
292 |
try:
|
293 |
tag = _firewall_tags[profile] |
294 |
except KeyError: |
295 |
raise ValueError("Unsopported Firewall Profile: %s" % profile) |
296 |
|
297 |
# Delete all firewall tags
|
298 |
for t in _firewall_tags.values(): |
299 |
rapi.DeleteInstanceTags(vm.backend_id, [t], dry_run=settings.TEST) |
300 |
|
301 |
rapi.AddInstanceTags(vm.backend_id, [tag], dry_run=settings.TEST) |
302 |
|
303 |
# XXX NOP ModifyInstance call to force process_net_status to run
|
304 |
# on the dispatcher
|
305 |
rapi.ModifyInstance(vm.backend_id, os_name=settings.GANETI_OS_PROVIDER) |