1 | #!/usr/local/bin/python |
---|
2 | |
---|
3 | import os,sys |
---|
4 | import re |
---|
5 | import string |
---|
6 | import copy |
---|
7 | import pickle |
---|
8 | import logging |
---|
9 | import random |
---|
10 | import subprocess |
---|
11 | |
---|
12 | from util import * |
---|
13 | from deter import fedid, generate_fedid |
---|
14 | from authorizer import authorizer, abac_authorizer |
---|
15 | from service_error import service_error |
---|
16 | from remote_service import xmlrpc_handler, soap_handler, service_caller |
---|
17 | |
---|
18 | from deter import topdl |
---|
19 | |
---|
20 | from access import access_base |
---|
21 | |
---|
22 | # Make log messages disappear if noone configures a fedd logger. This is |
---|
23 | # something of an incantation, but basically it creates a logger object |
---|
24 | # registered to fedd.access if no other module above us has. It's an extra |
---|
25 | # belt for the suspenders. |
---|
26 | class nullHandler(logging.Handler): |
---|
27 | def emit(self, record): pass |
---|
28 | |
---|
29 | fl = logging.getLogger("fedd.access") |
---|
30 | fl.addHandler(nullHandler()) |
---|
31 | |
---|
32 | |
---|
33 | # The plug-in itself. |
---|
34 | class access(access_base): |
---|
35 | """ |
---|
36 | This is a demonstration plug-in for fedd. It responds to all the |
---|
37 | experiment_control requests and keeps internal state. The allocations it |
---|
38 | makes are simple integers associated with each valid request. It makes use |
---|
39 | of the general routines in access.access_base. |
---|
40 | |
---|
41 | Detailed comments in the code and info at |
---|
42 | """ |
---|
43 | def __init__(self, config=None, auth=None): |
---|
44 | """ |
---|
45 | Initializer. Pulls parameters out of the ConfigParser's access |
---|
46 | section, and initializes simple internal state. This version reads a |
---|
47 | maximum integer to assign from the configuration file, while most other |
---|
48 | configuration entries are read by the base class. |
---|
49 | |
---|
50 | An access database in the cannonical format is also read as well as a |
---|
51 | state database that is a hash of internal state. Routines to |
---|
52 | manipulate these are in the base class, but specializations appear |
---|
53 | here. |
---|
54 | |
---|
55 | The access database maps users to a simple string. |
---|
56 | """ |
---|
57 | |
---|
58 | # Calling the base initializer, which reads canonical configuration |
---|
59 | # information and initializes canonical members. |
---|
60 | access_base.__init__(self, config, auth) |
---|
61 | # Reading the maximum integer parameter from the configuration file |
---|
62 | |
---|
63 | self.src_addr = config.get('access', 'interface_address') |
---|
64 | self.router = config.get('access', 'gateway') |
---|
65 | self.hostname = config.get('access', 'hostname') |
---|
66 | # Storage for ephemeral ssh keys and host files |
---|
67 | self.localdir = config.get('access', 'localdir') |
---|
68 | # File containing the routing entries for external networks |
---|
69 | self.external_networks = config.get('access', 'external_networks') |
---|
70 | # Comma-separated list of interfaces to export (may be empty) |
---|
71 | self.export_interfaces = config.get('access', 'export_interfaces') |
---|
72 | if self.export_interfaces is not None: |
---|
73 | self.export_interfaces = \ |
---|
74 | [ x.strip() for x in self.export_interfaces.split(',')] |
---|
75 | else: |
---|
76 | self.export_interfaces = [] |
---|
77 | |
---|
78 | # Comma separated list of connected nets to export - these won't work |
---|
79 | # in external_networks |
---|
80 | self.export_networks = config.get('access', 'export_networks') |
---|
81 | if self.export_networks is not None: |
---|
82 | self.export_networks = \ |
---|
83 | [ x.strip() for x in self.export_networks.split(',')] |
---|
84 | else: |
---|
85 | self.export_networks = [] |
---|
86 | |
---|
87 | # values for locations of zebra and ospfd. |
---|
88 | self.zebra = config.get('access', 'zebra') |
---|
89 | if self.zebra is None: |
---|
90 | self.zebra = '/usr/local/sbin/zebra' |
---|
91 | self.ospfd = config.get('access', 'ospfd') |
---|
92 | if self.ospfd is None: |
---|
93 | self.ospfd = '/usr/local/sbin/ospfd' |
---|
94 | |
---|
95 | # If this is a linux box that will be NATing, the iptables value |
---|
96 | # must be the path of the iptables command and the nat_interface must |
---|
97 | # be the nat interface. |
---|
98 | self.iptables = config.get('access', 'iptables') |
---|
99 | self.nat_interface = config.get('access', 'nat_interface') |
---|
100 | |
---|
101 | self.ssh_identity = None |
---|
102 | |
---|
103 | # hostname is the name of the ssh endpoint for the other side. That |
---|
104 | # side needs it to set up routing tables. If hostname is not |
---|
105 | # available, but an IP address is, use that. |
---|
106 | if self.hostname is None: |
---|
107 | if self.src_addr is None: |
---|
108 | raise service_error(service_error.server_config, |
---|
109 | 'Hostname or interface_address must be set in config') |
---|
110 | self.hostname = self.src_addr |
---|
111 | |
---|
112 | self.ssh_port = config.get('access', 'ssh_port', '22') |
---|
113 | |
---|
114 | # authorization information |
---|
115 | self.auth_type = config.get('access', 'auth_type') \ |
---|
116 | or 'abac' |
---|
117 | self.auth_dir = config.get('access', 'auth_dir') |
---|
118 | accessdb = config.get("access", "accessdb") |
---|
119 | # initialize the authorization system. We make a call to |
---|
120 | # read the access database that maps from authorization information |
---|
121 | # into local information. The local information is parsed by the |
---|
122 | # translator above. |
---|
123 | if self.auth_type == 'abac': |
---|
124 | # Load the current authorization state |
---|
125 | self.auth = abac_authorizer(load=self.auth_dir) |
---|
126 | self.access = [ ] |
---|
127 | if accessdb: |
---|
128 | try: |
---|
129 | self.read_access(accessdb) |
---|
130 | except EnvironmentError, e: |
---|
131 | self.log.error("Cannot read %s: %s" % \ |
---|
132 | (config.get("access", "accessdb"), e)) |
---|
133 | raise e |
---|
134 | else: |
---|
135 | raise service_error(service_error.internal, |
---|
136 | "Unknown auth_type: %s" % self.auth_type) |
---|
137 | |
---|
138 | # The superclass has read the state, but if this is the first run ever, |
---|
139 | # we must initialise the running flag. This plugin only supports one |
---|
140 | # connection, so StartSegment will fail when self.state['running'] is |
---|
141 | # true. |
---|
142 | self.state_lock.acquire() |
---|
143 | if 'running' not in self.state: |
---|
144 | self.state['running'] = False |
---|
145 | self.state_lock.release() |
---|
146 | |
---|
147 | # These dictionaries register the plug-in's local routines for handline |
---|
148 | # these four messages with the server code above. There's a version |
---|
149 | # for SOAP and XMLRPC, depending on which interfaces the plugin |
---|
150 | # supports. There's rarely a technical reason not to support one or |
---|
151 | # the other - the plugin code almost never deals with the transport - |
---|
152 | # but if a plug-in writer wanted to disable XMLRPC, they could leave |
---|
153 | # the self.xmlrpc_services dictionary empty. |
---|
154 | self.soap_services = {\ |
---|
155 | 'RequestAccess': soap_handler("RequestAccess", self.RequestAccess), |
---|
156 | 'ReleaseAccess': soap_handler("ReleaseAccess", self.ReleaseAccess), |
---|
157 | 'StartSegment': soap_handler("StartSegment", self.StartSegment), |
---|
158 | 'TerminateSegment': soap_handler("TerminateSegment", |
---|
159 | self.TerminateSegment), |
---|
160 | } |
---|
161 | self.xmlrpc_services = {\ |
---|
162 | 'RequestAccess': xmlrpc_handler('RequestAccess', |
---|
163 | self.RequestAccess), |
---|
164 | 'ReleaseAccess': xmlrpc_handler('ReleaseAccess', |
---|
165 | self.ReleaseAccess), |
---|
166 | 'StartSegment': xmlrpc_handler("StartSegment", self.StartSegment), |
---|
167 | 'TerminateSegment': xmlrpc_handler('TerminateSegment', |
---|
168 | self.TerminateSegment), |
---|
169 | } |
---|
170 | self.call_SetValue = service_caller('SetValue', log=self.log) |
---|
171 | self.call_GetValue = service_caller('GetValue', log=self.log) |
---|
172 | |
---|
173 | # ReleaseAccess come from the base class, this is a slightly modified |
---|
174 | # RequestAccess from the base that includes a fedAttr to force this side to |
---|
175 | # be active. |
---|
176 | def RequestAccess(self, req, fid): |
---|
177 | """ |
---|
178 | Handle an access request. Success here maps the requester into the |
---|
179 | local access control space and establishes state about that user keyed |
---|
180 | to a fedid. We also save a copy of the certificate underlying that |
---|
181 | fedid so this allocation can access configuration information and |
---|
182 | shared parameters on the experiment controller. |
---|
183 | """ |
---|
184 | |
---|
185 | self.log.info("RequestAccess called by %s" % fid) |
---|
186 | # The dance to get into the request body |
---|
187 | if req.has_key('RequestAccessRequestBody'): |
---|
188 | req = req['RequestAccessRequestBody'] |
---|
189 | else: |
---|
190 | raise service_error(service_error.req, "No request!?") |
---|
191 | |
---|
192 | # Base class lookup routine. If this fails, it throws a service |
---|
193 | # exception denying access that triggers a fault response back to the |
---|
194 | # caller. |
---|
195 | found, owners, proof = self.lookup_access(req, fid) |
---|
196 | self.log.info( |
---|
197 | "[RequestAccess] Access granted local creds %s" % found) |
---|
198 | # Make a fedid for this allocation |
---|
199 | allocID, alloc_cert = generate_fedid(subj="alloc", log=self.log) |
---|
200 | aid = unicode(allocID) |
---|
201 | |
---|
202 | # Store the data about this allocation: |
---|
203 | self.state_lock.acquire() |
---|
204 | self.state[aid] = { } |
---|
205 | self.state[aid]['user'] = found |
---|
206 | self.state[aid]['owners'] = owners |
---|
207 | self.state[aid]['auth'] = set() |
---|
208 | # Authorize the creating fedid and the principal representing the |
---|
209 | # allocation to manipulate it. |
---|
210 | self.append_allocation_authorization(aid, |
---|
211 | ((fid, allocID), (allocID, allocID))) |
---|
212 | self.write_state() |
---|
213 | self.state_lock.release() |
---|
214 | |
---|
215 | # Create a directory to stash the certificate in, ans stash it. |
---|
216 | try: |
---|
217 | f = open("%s/%s.pem" % (self.certdir, aid), "w") |
---|
218 | print >>f, alloc_cert |
---|
219 | f.close() |
---|
220 | except EnvironmentError, e: |
---|
221 | raise service_error(service_error.internal, |
---|
222 | "Can't open %s/%s : %s" % (self.certdir, aid, e)) |
---|
223 | self.log.debug('[RequestAccess] Returning allocation ID: %s' % allocID) |
---|
224 | msg = { |
---|
225 | 'allocID': { 'fedid': allocID }, |
---|
226 | 'fedAttr': [{ 'attribute': 'nat_portals', 'value': 'True' }], |
---|
227 | 'proof': proof.to_dict() |
---|
228 | } |
---|
229 | return msg |
---|
230 | |
---|
231 | def validate_topology(self, top): |
---|
232 | ''' |
---|
233 | Validate the topology. Desktops can only be single connections. |
---|
234 | Though the topology will include a portal and a node, the access |
---|
235 | controller will implement both on one node. |
---|
236 | |
---|
237 | As more capabilities are added to the contoller the constraints here |
---|
238 | will relax. |
---|
239 | ''' |
---|
240 | |
---|
241 | comps = [] |
---|
242 | for e in top.elements: |
---|
243 | if isinstance(e, topdl.Computer): comps.append(e) |
---|
244 | if len(comps) > 2: |
---|
245 | raise service_error(service_error.req, |
---|
246 | "Desktop only supports 1-node subexperiments") |
---|
247 | |
---|
248 | portals = 0 |
---|
249 | for c in comps: |
---|
250 | if c.get_attribute('portal') is not None: |
---|
251 | portals += 1 |
---|
252 | continue |
---|
253 | if len(c.interface) > 1: |
---|
254 | raise service_error(service_error.req, |
---|
255 | "Topology: Desktop Node has more than one interface") |
---|
256 | i = c.interface[0] |
---|
257 | if len(i.subs) > 1: |
---|
258 | raise service_error(service_error.req, |
---|
259 | "Topology: Desktop Node has more than " +\ |
---|
260 | "one substate on interface") |
---|
261 | sub = i.subs[0] |
---|
262 | for i in sub.interfaces: |
---|
263 | if i.element not in comps: |
---|
264 | raise service_error(service_error.req, |
---|
265 | "Topology: Desktop Node connected to non-portal") |
---|
266 | |
---|
267 | if portals > 1: |
---|
268 | raise service_error(service_error.req, |
---|
269 | "Desktop segment has more than one portal") |
---|
270 | return True |
---|
271 | |
---|
272 | def validate_connInfo(self, connInfo): |
---|
273 | if len(connInfo) != 1: |
---|
274 | raise service_error(service_error.req, |
---|
275 | "Desktop segment requests multiple connections") |
---|
276 | if connInfo[0]['type'] != 'ssh': |
---|
277 | raise service_error(service_error.req, |
---|
278 | "Desktop segment requires ssh connecton") |
---|
279 | return True |
---|
280 | |
---|
281 | def export_store_info(self, certfile, connInfo): |
---|
282 | ''' |
---|
283 | Tell the other portal node where to reach this desktop. The other side |
---|
284 | uses this information to set up routing, though the ssh_port is unused |
---|
285 | as the Desktop always initiates ssh connections. |
---|
286 | ''' |
---|
287 | values = { 'peer': self.hostname, 'ssh_port': self.ssh_port } |
---|
288 | for c in connInfo: |
---|
289 | for p in c.get('parameter', []): |
---|
290 | if p.get('type','') == 'input': continue |
---|
291 | pname = p.get('name', '') |
---|
292 | key = p.get('key', '') |
---|
293 | surl = p.get('store', '') |
---|
294 | if pname not in values: |
---|
295 | self.log('Unknown export parameter: %s' % pname) |
---|
296 | continue |
---|
297 | val = values[pname] |
---|
298 | req = { 'name': key, 'value': val } |
---|
299 | self.log.debug('Setting %s (%s) to %s on %s' % \ |
---|
300 | (pname, key, val, surl)) |
---|
301 | self.call_SetValue(surl, req, certfile) |
---|
302 | |
---|
303 | def set_route(self, dest, script, gw=None, src=None): |
---|
304 | if sys.platform.startswith('freebsd'): |
---|
305 | if src is not None and gw is not None: |
---|
306 | raise service_error(service_error.internal, |
---|
307 | 'FreeBSD will not route based on src address') |
---|
308 | elif src is not None: |
---|
309 | raise service_error(service_error.internal, |
---|
310 | 'FreeBSD will not route based on src address') |
---|
311 | elif gw is not None: |
---|
312 | print >>script, 'route add %s %s' % (dest, gw) |
---|
313 | elif sys.platform.startswith('linux'): |
---|
314 | if src is not None and gw is not None: |
---|
315 | print >>script, 'ip route add %s via %s src %s' % \ |
---|
316 | (dest, gw, src) |
---|
317 | elif src is not None: |
---|
318 | print >>script, 'ip route add %s src %s' % \ |
---|
319 | (dest, src) |
---|
320 | elif gw is not None: |
---|
321 | print >>script, 'ip route add %s via %s' % (dest, gw) |
---|
322 | else: |
---|
323 | raise service_error(service_error.internal, |
---|
324 | 'Unknown platform %s' % sys.platform) |
---|
325 | |
---|
326 | def unset_route(self, dest, script): |
---|
327 | rv = 0 |
---|
328 | if sys.platform.startswith('freebsd'): |
---|
329 | print >>script, 'route delete %s' % dest |
---|
330 | elif sys.platform.startswith('linux'): |
---|
331 | print >>script, 'ip route delete %s' % dest |
---|
332 | |
---|
333 | def find_a_peer(self, addr): |
---|
334 | ''' |
---|
335 | Find another node in the experiment that's on our subnet. This is a |
---|
336 | hack to handle the problem that we really cannot require the desktop to |
---|
337 | dynamically route. Will be improved by distributing static routes. |
---|
338 | ''' |
---|
339 | |
---|
340 | peer = None |
---|
341 | hosts = os.path.join(self.localdir, 'hosts') |
---|
342 | p = addr.rfind('.') |
---|
343 | if p == -1: |
---|
344 | raise service_error(service_error.req, 'bad address in topology') |
---|
345 | prefix = addr[0:p] |
---|
346 | addr_re = re.compile('(%s.\\d+)' % prefix) |
---|
347 | try: |
---|
348 | f = open(hosts, 'r') |
---|
349 | for line in f: |
---|
350 | m = addr_re.search(line) |
---|
351 | if m is not None and m.group(1) != addr: |
---|
352 | peer = m.group(1) |
---|
353 | break |
---|
354 | else: |
---|
355 | raise service_error(service_error.req, |
---|
356 | 'No other nodes in this subnet??') |
---|
357 | except EnvironmentError, e: |
---|
358 | raise service_error(service_error.internal, |
---|
359 | 'Cannot open %s: %s' % (e.filename, e.strerror)) |
---|
360 | return peer |
---|
361 | |
---|
362 | |
---|
363 | |
---|
364 | |
---|
365 | def configure_desktop(self, top, connInfo): |
---|
366 | ''' |
---|
367 | Build the connection. Establish routing to the peer if using a |
---|
368 | separate interface, wait until the other end confirms setup, establish |
---|
369 | the ssh layer-two tunnel (tap), assign the in-experiment IP address to |
---|
370 | the tunnel and establish routing to the experiment through the tap. |
---|
371 | ''' |
---|
372 | |
---|
373 | |
---|
374 | # get the peer and ssh port from the portal and our IP from the other |
---|
375 | peer = None |
---|
376 | port = None |
---|
377 | my_addr = None |
---|
378 | my_name = None |
---|
379 | for e in top.elements: |
---|
380 | if not isinstance(e, topdl.Computer): continue |
---|
381 | if e.get_attribute('portal') is None: |
---|
382 | my_name = e.name |
---|
383 | # there should be one interface with one IPv4 address |
---|
384 | if len(e.interface) <1 : |
---|
385 | raise service_error(service_error.internal, |
---|
386 | 'No interface on experiment node!?!?') |
---|
387 | my_addr = e.interface[0].get_attribute('ip4_address') |
---|
388 | else: |
---|
389 | for ci in connInfo: |
---|
390 | if ci.get('portal', '') != e.name: continue |
---|
391 | peer = ci.get('peer') |
---|
392 | port = '22' |
---|
393 | for a in ci.get('fedAttr', []): |
---|
394 | if a['attribute'] == 'ssh_port': port = a['value'] |
---|
395 | |
---|
396 | # XXX scan hosts for IP addresses and compose better routing entry |
---|
397 | |
---|
398 | if not all([peer, port, my_addr]): |
---|
399 | raise service_error(service_error.req, |
---|
400 | 'Cannot find all config parameters %s %s %s' % (peer, port, my_addr)) |
---|
401 | |
---|
402 | exp_peer = self.find_a_peer(my_addr) |
---|
403 | |
---|
404 | cscript = os.path.join(self.localdir, 'connect') |
---|
405 | dscript = os.path.join(self.localdir, 'disconnect') |
---|
406 | local_hosts = os.path.join(self.localdir, 'hosts') |
---|
407 | zebra_conf = os.path.join(self.localdir, 'zebra.conf') |
---|
408 | ospfd_conf = os.path.join(self.localdir, 'ospfd.conf') |
---|
409 | try: |
---|
410 | f = open(cscript, 'w') |
---|
411 | print >>f, '#!/bin/sh' |
---|
412 | # This picks the outgoing interface to the experiment using the |
---|
413 | # routing system. |
---|
414 | self.set_route(peer, f, self.router, self.src_addr) |
---|
415 | # Wait until the other end reports that it is configured py placing |
---|
416 | # a file this end can access into its local file system. Try once |
---|
417 | # a minute. |
---|
418 | print >>f,'while ! /usr/bin/scp -P %s -o "StrictHostKeyChecking no" -i %s %s:/usr/local/federation/etc/prep_done /dev/null; do' % (port, self.ssh_identity, peer) |
---|
419 | print >>f, 'sleep 60; done' |
---|
420 | # Important safety tip: ssh v 6.5 and above have a parsing bug |
---|
421 | # that means if you put -w before the -o "Tunnel ethernet" |
---|
422 | # parameter, you get a layer 3 tunnel instead of a layer 2 tunnel. |
---|
423 | # Don't move args in this line capricously. |
---|
424 | print >>f, ('ssh -p %s -o "Tunnel ethernet" -w 0:0 ' + \ |
---|
425 | '-o "StrictHostKeyChecking no" -i %s %s perl ' + |
---|
426 | '-I/usr/local/federation/lib ' + |
---|
427 | '/usr/local/federation/bin/setup_bridge.pl --tapno=0 ' + |
---|
428 | '--addr=%s --use_file &') % \ |
---|
429 | (port, self.ssh_identity, peer, my_addr) |
---|
430 | # This should give the tap a a chance to come up |
---|
431 | print >>f,'sleep 10' |
---|
432 | # Add experiment nodes to hosts |
---|
433 | print >>f, 'cp /etc/hosts /etc/hosts.DETER.fedd.hold' |
---|
434 | print >>f, 'echo "#--- BEGIN FEDD ADDITIONS ---" >> /etc/hosts' |
---|
435 | print >>f, 'cat %s >> /etc/hosts' % local_hosts |
---|
436 | print >>f, 'echo "#--- END FEDD ADDITIONS ---" >> /etc/hosts' |
---|
437 | # Assign tap address and route experiment connections through it. |
---|
438 | print >>f, 'ifconfig tap0 %s netmask 255.255.255.0 up' % \ |
---|
439 | my_addr |
---|
440 | print >>f, '%s -d -f %s' % (self.zebra, zebra_conf) |
---|
441 | print >>f, '%s -d -f %s' % (self.ospfd, ospfd_conf) |
---|
442 | if self.iptables is not None and self.nat_interface is not None: |
---|
443 | print >>f, '%s -t nat -A POSTROUTING -o %s -j MASQUERADE' %\ |
---|
444 | (self.iptables, self.nat_interface) |
---|
445 | print >>f, ('%s -A FORWARD -i %s -o tap0 -m state ' + |
---|
446 | '--state RELATED,ESTABLISHED -j ACCEPT') % \ |
---|
447 | (self.iptables, self.nat_interface) |
---|
448 | print >>f, '%s -A FORWARD -i tap0 -o %s -j ACCEPT' % \ |
---|
449 | (self.iptables, self.nat_interface) |
---|
450 | f.close() |
---|
451 | os.chmod(cscript, 0755) |
---|
452 | f = open(dscript, 'w') |
---|
453 | print >>f, '#!/bin/sh' |
---|
454 | if self.iptables is not None and self.nat_interface is not None: |
---|
455 | print >>f, '%s -t nat -D POSTROUTING -o %s -j MASQUERADE' %\ |
---|
456 | (self.iptables, self.nat_interface) |
---|
457 | print >>f, ('%s -D FORWARD -i %s -o tap0 -m state ' + |
---|
458 | '--state RELATED,ESTABLISHED -j ACCEPT') % \ |
---|
459 | (self.iptables, self.nat_interface) |
---|
460 | print >>f, '%s -D FORWARD -i tap0 -o %s -j ACCEPT' % \ |
---|
461 | (self.iptables, self.nat_interface) |
---|
462 | print >>f, 'pkill -f setup_bridge.pl' |
---|
463 | print >>f, 'mv /etc/hosts.DETER.fedd.hold /etc/hosts' |
---|
464 | print >>f, ('ssh -p %s -o "StrictHostKeyChecking no" -i %s %s ' + |
---|
465 | 'perl -I/usr/local/federation/lib ' + |
---|
466 | '/usr/local/federation/bin/unsetup_bridge.pl --tapno=0 ' + |
---|
467 | '--addr=%s') % \ |
---|
468 | (port, self.ssh_identity, peer, my_addr) |
---|
469 | print >>f, 'kill `cat /var/run/quagga/ospfd.pid`' |
---|
470 | print >>f, 'kill `cat /var/run/quagga/zebra.pid`' |
---|
471 | if self.iptables is not None and self.nat_interface is not None: |
---|
472 | print >>f, '%s -t nat -D POSTROUTING -o %s -j MASQUERADE' %\ |
---|
473 | (self.iptables, self.nat_interface) |
---|
474 | print >>f, ('%s -D FORWARD -i %s -o tap0 -m state ' + |
---|
475 | '--state RELATED,ESTABLISHED -j ACCEPT') % \ |
---|
476 | (self.iptables, self.nat_interface) |
---|
477 | print >>f, '%s -D FORWARD -i tap0 -o %s -j ACCEPT' % \ |
---|
478 | (self.iptables, self.nat_interface) |
---|
479 | f.close() |
---|
480 | os.chmod(dscript, 0755) |
---|
481 | f = open(zebra_conf, 'w') |
---|
482 | print >>f, 'hostname %s' % my_name |
---|
483 | print >>f, 'interface tap0' |
---|
484 | for i in self.export_interfaces: |
---|
485 | print >>f, 'interface %s' % i |
---|
486 | if self.external_networks is not None: |
---|
487 | try: |
---|
488 | extern = open(self.external_networks, 'r') |
---|
489 | if extern is not None: |
---|
490 | for l in extern: |
---|
491 | print >>f, "%s" % l.strip() |
---|
492 | extern.close() |
---|
493 | except EnvironmentError: |
---|
494 | # No external_networks or problem reading it, ignore |
---|
495 | pass |
---|
496 | f.close() |
---|
497 | os.chmod(zebra_conf, 0644) |
---|
498 | f = open(ospfd_conf, 'w') |
---|
499 | print >>f, 'hostname %s' % my_name |
---|
500 | print >>f, 'router ospf' |
---|
501 | print >>f, ' redistribute static' |
---|
502 | print >>f, ' network %s/24 area 0.0.0.2' % my_addr |
---|
503 | for i in self.export_networks: |
---|
504 | print >>f, ' network %s area 0.0.0.2' % i |
---|
505 | except EnvironmentError, e: |
---|
506 | raise service_error(service_error.internal, |
---|
507 | 'Cannot create connect %s: %s' % (e.filename, e.strerror)) |
---|
508 | script_log = open('/tmp/connect.log', 'w') |
---|
509 | subprocess.Popen(['sudo', '/bin/sh', cscript], stdout=script_log, |
---|
510 | stderr=script_log) |
---|
511 | return True |
---|
512 | |
---|
513 | def StartSegment(self, req, fid): |
---|
514 | """ |
---|
515 | Start a segment. In this simple skeleton, this means to parse the |
---|
516 | request and assign an unassigned integer to it. We store the integer |
---|
517 | in the persistent state. |
---|
518 | """ |
---|
519 | try: |
---|
520 | req = req['StartSegmentRequestBody'] |
---|
521 | # Get the request topology. If not present, a KeyError is thrown. |
---|
522 | topref = req['segmentdescription']['topdldescription'] |
---|
523 | # The fedid of the allocation we're attaching resources to |
---|
524 | auth_attr = req['allocID']['fedid'] |
---|
525 | except KeyError: |
---|
526 | raise service_error(service_error.req, "Badly formed request") |
---|
527 | |
---|
528 | # String version of the allocation ID for keying |
---|
529 | aid = "%s" % auth_attr |
---|
530 | # Authorization check |
---|
531 | access_ok, proof = self.auth.check_attribute(fid, auth_attr, |
---|
532 | with_proof=True) |
---|
533 | if not access_ok: |
---|
534 | raise service_error(service_error.access, "Access denied", |
---|
535 | proof=proof) |
---|
536 | else: |
---|
537 | # See if this is a replay of an earlier succeeded StartSegment - |
---|
538 | # sometimes SSL kills 'em. If so, replay the response rather than |
---|
539 | # redoing the allocation. |
---|
540 | self.state_lock.acquire() |
---|
541 | # Test and set :-) |
---|
542 | running = self.state['running'] |
---|
543 | self.state['running'] = True |
---|
544 | retval = self.state[aid].get('started', None) |
---|
545 | self.state_lock.release() |
---|
546 | if retval: |
---|
547 | self.log.warning( |
---|
548 | "[StartSegment] Duplicate StartSegment for %s: " \ |
---|
549 | % aid + \ |
---|
550 | "replaying response") |
---|
551 | return retval |
---|
552 | if running: |
---|
553 | self.log.debug('[StartSegment] already running') |
---|
554 | raise service_error(service_error.federant, |
---|
555 | 'Desktop is already in an experiment') |
---|
556 | |
---|
557 | certfile = "%s/%s.pem" % (self.certdir, aid) |
---|
558 | |
---|
559 | # Convert the topology into topdl data structures. Again, the |
---|
560 | # skeletion doesn't do anything with it, but this is how one parses a |
---|
561 | # topology request. |
---|
562 | if topref: topo = topdl.Topology(**topref) |
---|
563 | else: |
---|
564 | raise service_error(service_error.req, |
---|
565 | "Request missing segmentdescription'") |
---|
566 | |
---|
567 | err = None |
---|
568 | try: |
---|
569 | self.validate_topology(topo) |
---|
570 | |
---|
571 | # The attributes of the request. The ones we care about are the ssh |
---|
572 | # keys to operate the tunnel. |
---|
573 | attrs = req.get('fedAttr', []) |
---|
574 | for a in attrs: |
---|
575 | # Save the hosts and ssh_privkeys to our local dir |
---|
576 | if a['attribute'] in ('hosts', 'ssh_secretkey'): |
---|
577 | self.log.debug('Getting %s from %s' % \ |
---|
578 | (a['attribute'], a['value'])) |
---|
579 | get_url(a['value'], certfile, self.localdir, log=self.log) |
---|
580 | base = os.path.basename(a['value']) |
---|
581 | if a['attribute'] == 'ssh_secretkey': |
---|
582 | self.ssh_identity = os.path.join(self.localdir, base) |
---|
583 | os.chmod(os.path.join(self.localdir, base), 0600) |
---|
584 | else: |
---|
585 | self.log.debug('Ignoring attribute %s' % a['attribute']) |
---|
586 | |
---|
587 | # Gather connection information and exchange parameters. |
---|
588 | connInfo = req.get('connection', []) |
---|
589 | self.validate_connInfo(connInfo) |
---|
590 | self.export_store_info(certfile, connInfo) |
---|
591 | self.import_store_info(certfile, connInfo) |
---|
592 | |
---|
593 | #build it |
---|
594 | self.configure_desktop(topo, connInfo) |
---|
595 | except service_error, e: |
---|
596 | err = e |
---|
597 | |
---|
598 | # Save the information |
---|
599 | if err is None: |
---|
600 | # It's possible that the StartSegment call gets retried (!). if |
---|
601 | # the 'started' key is in the allocation, we'll return it rather |
---|
602 | # than redo the setup. The integer allocation was saved when we |
---|
603 | # made it. |
---|
604 | self.state_lock.acquire() |
---|
605 | self.state[aid]['started'] = { |
---|
606 | 'allocID': req['allocID'], |
---|
607 | 'allocationLog': "Allocatation complete", |
---|
608 | 'segmentdescription': { 'topdldescription': topo.to_dict() }, |
---|
609 | 'proof': proof.to_dict(), |
---|
610 | } |
---|
611 | retval = copy.deepcopy(self.state[aid]['started']) |
---|
612 | self.write_state() |
---|
613 | self.state_lock.release() |
---|
614 | else: |
---|
615 | # Something bad happened - clear the "running" flag so we can try |
---|
616 | # again |
---|
617 | self.state_lock.acquire() |
---|
618 | self.state['running'] = False |
---|
619 | self.state_lock.release() |
---|
620 | raise err |
---|
621 | |
---|
622 | return retval |
---|
623 | |
---|
624 | def TerminateSegment(self, req, fid): |
---|
625 | """ |
---|
626 | Remove the resources associated with th eallocation and stop the music. |
---|
627 | In this example, this simply means removing the integer we allocated. |
---|
628 | """ |
---|
629 | # Gather the same access information as for Start Segment |
---|
630 | try: |
---|
631 | req = req['TerminateSegmentRequestBody'] |
---|
632 | except KeyError: |
---|
633 | raise service_error(service_error.req, "Badly formed request") |
---|
634 | |
---|
635 | auth_attr = req['allocID']['fedid'] |
---|
636 | aid = "%s" % auth_attr |
---|
637 | |
---|
638 | self.log.debug("Terminate request for %s" %aid) |
---|
639 | # Check authorization |
---|
640 | access_ok, proof = self.auth.check_attribute(fid, auth_attr, |
---|
641 | with_proof=True) |
---|
642 | if not access_ok: |
---|
643 | raise service_error(service_error.access, "Access denied", |
---|
644 | proof=proof) |
---|
645 | cscript = os.path.join(self.localdir, 'connect') |
---|
646 | dscript = os.path.join(self.localdir, 'disconnect') |
---|
647 | # Do the work of disconnecting |
---|
648 | if os.path.exists(dscript): |
---|
649 | self.log.debug('calling %s' % dscript) |
---|
650 | rv = subprocess.call(['sudo', '/bin/sh', dscript]) |
---|
651 | if rv != 0: |
---|
652 | self.log.warning('%s had an error: %d' % (dscript, rv)) |
---|
653 | else: |
---|
654 | self.log.warn('No disconnection script!?') |
---|
655 | |
---|
656 | try: |
---|
657 | for bfn in os.listdir(self.localdir): |
---|
658 | fn = os.path.join(self.localdir, bfn) |
---|
659 | self.log.debug('Removing %s' % fn) |
---|
660 | if os.path.exists(fn): |
---|
661 | os.remove(fn) |
---|
662 | except EnvironmentError, e: |
---|
663 | self.log.warn('Failed to remove %s: %s' % (e.filename, e.strerror)) |
---|
664 | |
---|
665 | self.ssh_identity = None |
---|
666 | |
---|
667 | self.state_lock.acquire() |
---|
668 | self.state['running'] = False |
---|
669 | self.state_lock.release() |
---|
670 | |
---|
671 | return { 'allocID': req['allocID'], 'proof': proof.to_dict() } |
---|