root / logic / backend.py @ f040c416
History | View | Annotate | Download (9.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 |
from django.conf import settings |
35 |
from django.db import transaction |
36 |
|
37 |
from synnefo.db.models import (VirtualMachine, Network, NetworkInterface, |
38 |
NetworkLink) |
39 |
from synnefo.logic import utils |
40 |
from synnefo.util.rapi import GanetiRapiClient |
41 |
|
42 |
|
43 |
rapi = GanetiRapiClient(*settings.GANETI_CLUSTER_INFO) |
44 |
|
45 |
|
46 |
def process_op_status(vm, jobid, opcode, status, logmsg): |
47 |
"""Process a job progress notification from the backend
|
48 |
|
49 |
Process an incoming message from the backend (currently Ganeti).
|
50 |
Job notifications with a terminating status (sucess, error, or canceled),
|
51 |
also update the operating state of the VM.
|
52 |
|
53 |
"""
|
54 |
if (opcode not in [x[0] for x in VirtualMachine.BACKEND_OPCODES] or |
55 |
status not in [x[0] for x in VirtualMachine.BACKEND_STATUSES]): |
56 |
raise VirtualMachine.InvalidBackendMsgError(opcode, status)
|
57 |
|
58 |
vm.backendjobid = jobid |
59 |
vm.backendjobstatus = status |
60 |
vm.backendopcode = opcode |
61 |
vm.backendlogmsg = logmsg |
62 |
|
63 |
# Notifications of success change the operating state
|
64 |
if status == 'success' and VirtualMachine.OPER_STATE_FROM_OPCODE[opcode] is not None: |
65 |
utils.update_state(vm, VirtualMachine.OPER_STATE_FROM_OPCODE[opcode]) |
66 |
# Set the deleted flag explicitly, to cater for admin-initiated removals
|
67 |
if opcode == 'OP_INSTANCE_REMOVE': |
68 |
vm.deleted = True
|
69 |
|
70 |
# Special case: if OP_INSTANCE_CREATE fails --> ERROR
|
71 |
if status in ('canceled', 'error') and opcode == 'OP_INSTANCE_CREATE': |
72 |
utils.update_state(vm, 'ERROR')
|
73 |
# Any other notification of failure leaves the operating state unchanged
|
74 |
|
75 |
vm.save() |
76 |
|
77 |
|
78 |
@transaction.commit_on_success
|
79 |
def process_net_status(vm, nics): |
80 |
"""Process a net status notification from the backend
|
81 |
|
82 |
Process an incoming message from the Ganeti backend,
|
83 |
detailing the NIC configuration of a VM instance.
|
84 |
|
85 |
Update the state of the VM in the DB accordingly.
|
86 |
"""
|
87 |
|
88 |
vm.nics.all().delete() |
89 |
for i, nic in enumerate(nics): |
90 |
if i == 0: |
91 |
net = Network.objects.get(public=True)
|
92 |
else:
|
93 |
try:
|
94 |
link = NetworkLink.objects.get(name=nic['link'])
|
95 |
except NetworkLink.DoesNotExist:
|
96 |
# Cannot find an instance of NetworkLink for
|
97 |
# the link attribute specified in the notification
|
98 |
raise NetworkLink.DoesNotExist("Cannot find a NetworkLink " |
99 |
"object for link='%s'" % nic['link']) |
100 |
net = link.network |
101 |
if net is None: |
102 |
raise Network.DoesNotExist("NetworkLink for link='%s' not " |
103 |
"associated with an existing Network instance." %
|
104 |
nic['link'])
|
105 |
|
106 |
vm.nics.create( |
107 |
network=net, |
108 |
index=i, |
109 |
mac=nic.get('mac', ''), |
110 |
ipv4=nic.get('ip', ''), |
111 |
ipv6=nic.get('ipv6','')) |
112 |
vm.save() |
113 |
|
114 |
|
115 |
def start_action(vm, action): |
116 |
"""Update the state of a VM when a new action is initiated."""
|
117 |
if not action in [x[0] for x in VirtualMachine.ACTIONS]: |
118 |
raise VirtualMachine.InvalidActionError(action)
|
119 |
|
120 |
# No actions to deleted and no actions beside destroy to suspended VMs
|
121 |
if vm.deleted:
|
122 |
raise VirtualMachine.DeletedError
|
123 |
|
124 |
# No actions to machines being built. They may be destroyed, however.
|
125 |
if vm.operstate == 'BUILD' and action != 'DESTROY': |
126 |
raise VirtualMachine.BuildingError
|
127 |
|
128 |
vm.action = action |
129 |
vm.backendjobid = None
|
130 |
vm.backendopcode = None
|
131 |
vm.backendjobstatus = None
|
132 |
vm.backendlogmsg = None
|
133 |
|
134 |
# Update the relevant flags if the VM is being suspended or destroyed
|
135 |
if action == "DESTROY": |
136 |
vm.deleted = True
|
137 |
elif action == "SUSPEND": |
138 |
vm.suspended = True
|
139 |
elif action == "START": |
140 |
vm.suspended = False
|
141 |
vm.save() |
142 |
|
143 |
|
144 |
def create_instance(vm, flavor, image, password): |
145 |
|
146 |
nic = {'ip': 'pool', 'mode': 'routed', 'link': settings.GANETI_PUBLIC_LINK} |
147 |
|
148 |
return rapi.CreateInstance(
|
149 |
mode='create',
|
150 |
name=vm.backend_id, |
151 |
disk_template='plain',
|
152 |
disks=[{"size": 4000}], #FIXME: Always ask for a 4GB disk for now |
153 |
nics=[nic], |
154 |
os='image+default',
|
155 |
ip_check=False,
|
156 |
name_check=False,
|
157 |
# Do not specific a node explicitly, have
|
158 |
# Ganeti use an iallocator instead
|
159 |
#
|
160 |
# pnode=rapi.GetNodes()[0]
|
161 |
dry_run=settings.TEST, |
162 |
beparams=dict(auto_balance=True, vcpus=flavor.cpu, memory=flavor.ram), |
163 |
osparams=dict(img_id=image.backend_id, img_passwd=password,
|
164 |
img_format=image.format)) |
165 |
|
166 |
|
167 |
def delete_instance(vm): |
168 |
start_action(vm, 'DESTROY')
|
169 |
rapi.DeleteInstance(vm.backend_id, dry_run=settings.TEST) |
170 |
vm.nics.all().delete() |
171 |
|
172 |
|
173 |
def reboot_instance(vm, reboot_type): |
174 |
assert reboot_type in ('soft', 'hard') |
175 |
rapi.RebootInstance(vm.backend_id, reboot_type, dry_run=settings.TEST) |
176 |
|
177 |
|
178 |
def startup_instance(vm): |
179 |
start_action(vm, 'START')
|
180 |
rapi.StartupInstance(vm.backend_id, dry_run=settings.TEST) |
181 |
|
182 |
|
183 |
def shutdown_instance(vm): |
184 |
start_action(vm, 'STOP')
|
185 |
rapi.ShutdownInstance(vm.backend_id, dry_run=settings.TEST) |
186 |
|
187 |
|
188 |
def get_instance_console(vm): |
189 |
return rapi.GetInstanceConsole(vm.backend_id)
|
190 |
|
191 |
|
192 |
def request_status_update(vm): |
193 |
return rapi.GetInstanceInfo(vm.backend_id)
|
194 |
|
195 |
|
196 |
def get_job_status(jobid): |
197 |
return rapi.GetJobStatus(jobid)
|
198 |
|
199 |
|
200 |
def update_status(vm, status): |
201 |
utils.update_state(vm, status) |
202 |
|
203 |
def create_network_link(): |
204 |
try:
|
205 |
last = NetworkLink.objects.order_by('-index')[0] |
206 |
index = last.index + 1
|
207 |
except IndexError: |
208 |
index = 1
|
209 |
|
210 |
if index <= settings.GANETI_MAX_LINK_NUMBER:
|
211 |
name = '%s%d' % (settings.GANETI_LINK_PREFIX, index)
|
212 |
return NetworkLink.objects.create(index=index, name=name,
|
213 |
available=True)
|
214 |
return None # All link slots are filled |
215 |
|
216 |
@transaction.commit_on_success
|
217 |
def create_network(name, owner): |
218 |
try:
|
219 |
link = NetworkLink.objects.filter(available=True)[0] |
220 |
except IndexError: |
221 |
link = create_network_link() |
222 |
if not link: |
223 |
return None |
224 |
|
225 |
network = Network.objects.create( |
226 |
name=name, |
227 |
owner=owner, |
228 |
state='ACTIVE',
|
229 |
link=link) |
230 |
|
231 |
link.network = network |
232 |
link.available = False
|
233 |
link.save() |
234 |
|
235 |
return network
|
236 |
|
237 |
@transaction.commit_on_success
|
238 |
def delete_network(net): |
239 |
link = net.link |
240 |
if link.name != settings.GANETI_NULL_LINK:
|
241 |
link.available = True
|
242 |
link.network = None
|
243 |
link.save() |
244 |
|
245 |
for vm in net.machines.all(): |
246 |
disconnect_from_network(vm, net) |
247 |
vm.save() |
248 |
net.state = 'DELETED'
|
249 |
net.save() |
250 |
|
251 |
def connect_to_network(vm, net): |
252 |
nic = {'mode': 'bridged', 'link': net.link.name} |
253 |
rapi.ModifyInstance(vm.backend_id, |
254 |
nics=[('add', nic)],
|
255 |
dry_run=settings.TEST) |
256 |
|
257 |
def disconnect_from_network(vm, net): |
258 |
nics = vm.nics.filter(network__public=False).order_by('index') |
259 |
new_nics = [nic for nic in nics if nic.network != net] |
260 |
if new_nics == nics:
|
261 |
return # Nothing to remove |
262 |
ops = [('remove', {})]
|
263 |
for i, nic in enumerate(new_nics): |
264 |
ops.append((i + 1, {
|
265 |
'mode': 'bridged', |
266 |
'link': nic.network.link.name}))
|
267 |
rapi.ModifyInstance(vm.backend_id, nics=ops, dry_run=settings.TEST) |
268 |
|
269 |
|
270 |
_firewall_tags = { |
271 |
'ENABLED': settings.GANETI_FIREWALL_ENABLED_TAG,
|
272 |
'DISABLED': settings.GANETI_FIREWALL_DISABLED_TAG,
|
273 |
'PROTECTED': settings.GANETI_FIREWALL_PROTECTED_TAG}
|
274 |
|
275 |
def set_firewall_profile(vm, profile): |
276 |
try:
|
277 |
tag = _firewall_tags[profile] |
278 |
except KeyError: |
279 |
raise ValueError("Unsopported Firewall Profile: %s" % profile) |
280 |
|
281 |
# Delete all firewall tags
|
282 |
rapi.DeleteInstanceTags(vm.backend_id, _firewall_tags.values(), |
283 |
dry_run=settings.TEST) |
284 |
|
285 |
rapi.AddInstanceTags(vm.backend_id, [tag], dry_run=settings.TEST) |