A small one-node SFA/planetlab test worked.
[nepi.git] / src / nepi / testbeds / planetlab / interfaces.py
1 # -*- coding: utf-8 -*-
2
3 from constants import TESTBED_ID
4 import nepi.util.ipaddr2 as ipaddr2
5 import nepi.util.server as server
6 import plcapi
7 import subprocess
8 import os
9 import os.path
10 import random
11 import ipaddr
12 import functools
13
14 import tunproto
15
16 class NodeIface(object):
17     def __init__(self, api=None):
18         if not api:
19             api = plcapi.PLCAPI()
20         self._api = api
21         
22         # Attributes
23         self.primary = True
24
25         # These get initialized at configuration time
26         self.address = None
27         self.lladdr = None
28         self.netprefix = None
29         self.netmask = None
30         self.broadcast = True
31         self._interface_id = None
32
33         # These get initialized when the iface is connected to its node
34         self.node = None
35
36         # These get initialized when the iface is connected to the internet
37         self.has_internet = False
38
39     def __str__(self):
40         return "%s<ip:%s/%s up mac:%s>" % (
41             self.__class__.__name__,
42             self.address, self.netmask,
43             self.lladdr,
44         )
45     
46     __repr__ = __str__
47
48     def add_address(self, address, netprefix, broadcast):
49         raise RuntimeError, "Cannot add explicit addresses to public interface"
50     
51     def pick_iface(self, siblings):
52         """
53         Picks an interface using the PLCAPI to query information about the node.
54         
55         Needs an assigned node.
56         
57         Params:
58             siblings: other NodeIface elements attached to the same node
59         """
60         
61         if self.node is None or self.node._node_id is None:
62             raise RuntimeError, "Cannot pick interface without an assigned node"
63       
64         # HACK: SFA doesnt give the node_id!!
65         if not isinstance(self.node._node_id, int):
66             node_data = self._api.GetNodes(filters={'hostname':self.node.hostname}, fields=('node_id',))[0]
67             node_id = node_data['node_id']
68         else:
69             node_id = self.node._node_id
70
71         avail = self._api.GetInterfaces(
72             node_id=node_id, 
73             is_primary=self.primary,
74             fields=('interface_id','mac','netmask','ip') )
75         
76         used = set([sibling._interface_id for sibling in siblings
77                     if sibling._interface_id is not None])
78         
79         for candidate in avail:
80             candidate_id = candidate['interface_id']
81             if candidate_id not in used:
82                 # pick it!
83                 self._interface_id = candidate_id
84                 self.address = candidate['ip']
85                 self.lladdr = candidate['mac']
86                 self.netprefix = candidate['netmask']
87                 self.netmask = ipaddr2.ipv4_dot2mask(self.netprefix) if self.netprefix else None
88                 return
89         else:
90             raise RuntimeError, "Cannot configure interface: cannot find suitable interface in PlanetLab node"
91
92     def validate(self):
93         if not self.has_internet:
94             raise RuntimeError, "All external interface devices must be connected to the Internet"
95     
96
97 class _CrossIface(object):
98     def __init__(self, proto, addr, port, cipher):
99         self.tun_proto = proto
100         self.tun_addr = addr
101         self.tun_port = port
102         self.tun_cipher = cipher
103
104         # Attributes
105         self.address = None
106         self.netprefix = None
107         self.netmask = None
108  
109         # Cannot access cross peers
110         self.peer_proto_impl = None
111     
112     def __str__(self):
113         return "%s%r" % (
114             self.__class__.__name__,
115             ( self.tun_proto,
116               self.tun_addr,
117               self.tun_port,
118               self.tun_cipher ) 
119         )
120     
121     __repr__ = __str__
122
123 class TunIface(object):
124     _PROTO_MAP = tunproto.TUN_PROTO_MAP
125     _KIND = 'TUN'
126
127     def __init__(self, api=None):
128         if not api:
129             api = plcapi.PLCAPI()
130         self._api = api
131         
132         # Attributes
133         self.address = None
134         self.netprefix = None
135         self.netmask = None
136         
137         self.up = None
138         self.mtu = None
139         self.snat = False
140         self.txqueuelen = 1000
141         self.pointopoint = None
142         self.multicast = False
143         self.bwlimit = None
144         
145         # Enabled traces
146         self.capture = False
147
148         # These get initialized when the iface is connected to its node
149         self.node = None
150         
151         # These get initialized when the iface is connected to any filter
152         self.filter_module = None
153         self.multicast_forwarder = None
154         
155         # These get initialized when the iface is configured
156         self.external_iface = None
157         
158         # These get initialized when the iface is configured
159         # They're part of the TUN standard attribute set
160         self.tun_port = None
161         self.tun_addr = None
162         self.tun_cipher = "AES"
163         
164         # These get initialized when the iface is connected to its peer
165         self.peer_iface = None
166         self.peer_proto = None
167         self.peer_addr = None
168         self.peer_port = None
169         self.peer_proto_impl = None
170         self._delay_recover = False
171
172         # same as peer proto, but for execute-time standard attribute lookups
173         self.tun_proto = None 
174         
175         
176         # Generate an initial random cryptographic key to use for tunnelling
177         # Upon connection, both endpoints will agree on a common one based on
178         # this one.
179         self.tun_key = ( ''.join(map(chr, [ 
180                     r.getrandbits(8) 
181                     for i in xrange(32) 
182                     for r in (random.SystemRandom(),) ])
183                 ).encode("base64").strip() )        
184         
185
186     def __str__(self):
187         return "%s<ip:%s/%s %s%s%s>" % (
188             self.__class__.__name__,
189             self.address, self.netprefix,
190             " up" if self.up else " down",
191             " snat" if self.snat else "",
192             (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
193         )
194     
195     __repr__ = __str__
196     
197     @property
198     def if_name(self):
199         if self.peer_proto_impl:
200             return self.peer_proto_impl.if_name
201
202     def routes_here(self, route):
203         """
204         Returns True if the route should be attached to this interface
205         (ie, it references a gateway in this interface's network segment)
206         """
207         if self.address and self.netprefix:
208             addr, prefix = self.address, self.netprefix
209             pointopoint = self.pointopoint
210             if not pointopoint and self.peer_iface:
211                 pointopoint = self.peer_iface.address
212             
213             if pointopoint:
214                 prefix = 32
215                 
216             dest, destprefix, nexthop, metric = route
217             
218             myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
219             gwIp = ipaddr.IPNetwork(nexthop)
220             
221             if pointopoint:
222                 peerIp = ipaddr.IPNetwork(pointopoint)
223                 
224                 if gwIp == peerIp:
225                     return True
226             else:
227                 if gwIp in myNet:
228                     return True
229         return False
230     
231     def add_address(self, address, netprefix, broadcast):
232         if (self.address or self.netprefix or self.netmask) is not None:
233             raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
234         if broadcast:
235             raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
236         
237         self.address = address
238         self.netprefix = netprefix
239         self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
240     
241     def validate(self):
242         if not self.node:
243             raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
244         if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
245             raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
246         if not self.address or not self.netprefix or not self.netmask:
247             raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
248         if self.filter_module and self.peer_proto not in ('udp','tcp',None):
249             raise RuntimeError, "Miscofnigured TUN: %s - filtered tunnels only work with udp or tcp links" % (self,)
250         if self.tun_cipher != 'PLAIN' and self.peer_proto not in ('udp','tcp',None):
251             raise RuntimeError, "Miscofnigured TUN: %s - ciphered tunnels only work with udp or tcp links" % (self,)
252     
253     def _impl_instance(self, home_path):
254         impl = self._PROTO_MAP[self.peer_proto](
255             self, self.peer_iface, home_path, self.tun_key)
256         impl.port = self.tun_port
257         impl.cross_slice = not self.peer_iface or isinstance(self.peer_iface, _CrossIface)
258         return impl
259     
260     def recover(self):
261         if self.peer_proto:
262             self.peer_proto_impl = self._impl_instance(
263                 self._home_path)
264             self.peer_proto_impl.recover()
265         else:
266             self._delay_recover = True
267     
268     def prepare(self, home_path):
269         if not self.peer_iface and (self.peer_proto and self.peer_addr):
270             # Ad-hoc peer_iface
271             self.peer_iface = _CrossIface(
272                 self.peer_proto,
273                 self.peer_addr,
274                 self.peer_port,
275                 self.peer_cipher)
276         if self.peer_iface:
277             if not self.peer_proto_impl:
278                 self.peer_proto_impl = self._impl_instance(home_path)
279             if self._delay_recover:
280                 self.peer_proto_impl.recover()
281     
282     def launch(self):
283         if self.peer_proto_impl:
284             self.peer_proto_impl.launch()
285     
286     def cleanup(self):
287         if self.peer_proto_impl:
288             self.peer_proto_impl.shutdown()
289
290     def destroy(self):
291         if self.peer_proto_impl:
292             self.peer_proto_impl.destroy()
293             self.peer_proto_impl = None
294
295     def wait(self):
296         if self.peer_proto_impl:
297             self.peer_proto_impl.wait()
298
299     def sync_trace(self, local_dir, whichtrace, tracemap = None):
300         if self.peer_proto_impl:
301             return self.peer_proto_impl.sync_trace(local_dir, whichtrace,
302                     tracemap)
303         else:
304             return None
305
306     def remote_trace_path(self, whichtrace, tracemap = None):
307         if self.peer_proto_impl:
308             return self.peer_proto_impl.remote_trace_path(whichtrace, tracemap)
309         else:
310             return None
311
312     def remote_trace_name(self, whichtrace):
313         return whichtrace
314
315 class TapIface(TunIface):
316     _PROTO_MAP = tunproto.TAP_PROTO_MAP
317     _KIND = 'TAP'
318
319 # Yep, it does nothing - yet
320 class Internet(object):
321     def __init__(self, api=None):
322         if not api:
323             api = plcapi.PLCAPI()
324         self._api = api
325
326 class NetPipe(object):
327     def __init__(self, api=None):
328         if not api:
329             api = plcapi.PLCAPI()
330         self._api = api
331
332         # Attributes
333         self.mode = None
334         self.addrList = None
335         self.portList = None
336         
337         self.plrIn = None
338         self.bwIn = None
339         self.delayIn = None
340
341         self.plrOut = None
342         self.bwOut = None
343         self.delayOut = None
344         
345         # These get initialized when the pipe is connected to its node
346         self.node = None
347         self.configured = False
348     
349     def validate(self):
350         if not self.mode:
351             raise RuntimeError, "Undefined NetPipe mode"
352         if not self.portList:
353             raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
354         if not (self.plrIn or self.bwIn or self.delayIn):
355             raise RuntimeError, "Undefined NetPipe inbound characteristics"
356         if not (self.plrOut or self.bwOut or self.delayOut):
357             raise RuntimeError, "Undefined NetPipe outbound characteristics"
358         if not self.node:
359             raise RuntimeError, "Unconnected NetPipe"
360     
361     def _add_pipedef(self, bw, plr, delay, options):
362         if delay:
363             options.extend(("delay","%dms" % (delay,)))
364         if bw:
365             options.extend(("bw","%.8fMbit/s" % (bw,)))
366         if plr:
367             options.extend(("plr","%.8f" % (plr,)))
368     
369     def _get_ruledef(self):
370         scope = "%s%s%s" % (
371             self.portList,
372             "@" if self.addrList else "",
373             self.addrList or "",
374         )
375         
376         options = []
377         if self.bwIn or self.plrIn or self.delayIn:
378             options.append("IN")
379             self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
380         if self.bwOut or self.plrOut or self.delayOut:
381             options.append("OUT")
382             self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
383         options = ' '.join(options)
384         
385         return (scope,options)
386     
387     def recover(self):
388         # Rules are safe on their nodes
389         self.configured = True
390
391     def configure(self):
392         # set up rule
393         scope, options = self._get_ruledef()
394         command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
395         
396         (out,err),proc = server.popen_ssh_command(
397             command,
398             host = self.node.hostname,
399             port = None,
400             user = self.node.slicename,
401             agent = None,
402             ident_key = self.node.ident_path,
403             server_key = self.node.server_key
404             )
405     
406         if proc.wait():
407             raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
408         
409         # we have to clean up afterwards
410         self.configured = True
411     
412     def refresh(self):
413         if self.configured:
414             # refresh rule
415             scope, options = self._get_ruledef()
416             command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
417             
418             (out,err),proc = server.popen_ssh_command(
419                 command,
420                 host = self.node.hostname,
421                 port = None,
422                 user = self.node.slicename,
423                 agent = None,
424                 ident_key = self.node.ident_path,
425                 server_key = self.node.server_key
426                 )
427         
428             if proc.wait():
429                 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
430     
431     def cleanup(self):
432         if self.configured:
433             # remove rule
434             scope, options = self._get_ruledef()
435             command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
436             
437             (out,err),proc = server.popen_ssh_command(
438                 command,
439                 host = self.node.hostname,
440                 port = None,
441                 user = self.node.slicename,
442                 agent = None,
443                 ident_key = self.node.ident_path,
444                 server_key = self.node.server_key
445                 )
446         
447             if proc.wait():
448                 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
449             
450             self.configured = False
451     
452     def sync_trace(self, local_dir, whichtrace):
453         if whichtrace != 'netpipeStats':
454             raise ValueError, "Unsupported trace %s" % (whichtrace,)
455         
456         local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
457         
458         # create parent local folders
459         proc = subprocess.Popen(
460             ["mkdir", "-p", os.path.dirname(local_path)],
461             stdout = open("/dev/null","w"),
462             stdin = open("/dev/null","r"))
463
464         if proc.wait():
465             raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
466         
467         (out,err),proc = server.popen_ssh_command(
468             "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
469             host = self.node.hostname,
470             port = None,
471             user = self.node.slicename,
472             agent = None,
473             ident_key = self.node.ident_path,
474             server_key = self.node.server_key
475             )
476         
477         if proc.wait():
478             raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
479         
480         # dump results to file
481         f = open(local_path, "wb")
482         f.write(err or "")
483         f.write(out or "")
484         f.close()
485         
486         return local_path
487     
488 class TunFilter(object):
489     _TRACEMAP = {
490         # tracename : (remotename, localname)
491     }
492     
493     def __init__(self, api=None):
494         if not api:
495             api = plcapi.PLCAPI()
496         self._api = api
497         
498         # Attributes
499         self.module = None
500         self.args = None
501
502         # These get initialised when the filter is connected
503         self.peer_guid = None
504         self.peer_proto = None
505         self.iface_guid = None
506         self.peer = None
507         self.iface = None
508     
509     def _get(what, self):
510         wref = self.iface
511         if wref:
512             wref = wref()
513         if wref:
514             return getattr(wref, what)
515         else:
516             return None
517
518     def _set(what, self, val):
519         wref = self.iface
520         if wref:
521             wref = wref()
522         if wref:
523             setattr(wref, what, val)
524     
525     tun_proto = property(
526         functools.partial(_get, 'tun_proto'),
527         functools.partial(_set, 'tun_proto') )
528     tun_addr = property(
529         functools.partial(_get, 'tun_addr'),
530         functools.partial(_set, 'tun_addr') )
531     tun_port = property(
532         functools.partial(_get, 'tun_port'),
533         functools.partial(_set, 'tun_port') )
534     tun_key = property(
535         functools.partial(_get, 'tun_key'),
536         functools.partial(_set, 'tun_key') )
537     tun_cipher = property(
538         functools.partial(_get, 'tun_cipher'),
539         functools.partial(_set, 'tun_cipher') )
540     
541     del _get
542     del _set
543
544     def remote_trace_path(self, whichtrace):
545         iface = self.iface()
546         if iface is not None:
547             return iface.remote_trace_path(whichtrace, self._TRACEMAP)
548         return None
549
550     def remote_trace_name(self, whichtrace):
551         iface = self.iface()
552         if iface is not None:
553             return iface.remote_trace_name(whichtrace, self._TRACEMAP)
554         return None
555
556     def sync_trace(self, local_dir, whichtrace):
557         iface = self.iface()
558         if iface is not None:
559             return iface.sync_trace(local_dir, whichtrace, self._TRACEMAP)
560         return None
561
562 class ClassQueueFilter(TunFilter):
563     _TRACEMAP = {
564         # tracename : (remotename, localname)
565         'dropped_stats' : ('dropped_stats', 'dropped_stats')
566     }
567     
568     def __init__(self, api=None):
569         super(ClassQueueFilter, self).__init__(api)
570         # Attributes
571         self.module = "classqueue.py"
572
573 class ToSQueueFilter(TunFilter):
574     def __init__(self, api=None):
575         super(ToSQueueFilter, self).__init__(api)
576         # Attributes
577         self.module = "tosqueue.py"
578