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