2 # -*- coding: utf-8 -*-
4 from constants import TESTBED_ID
5 import nepi.util.ipaddr2 as ipaddr2
6 import nepi.util.server as server
17 class NodeIface(object):
18 def __init__(self, api=None):
26 # These get initialized at configuration time
32 self._interface_id = None
34 # These get initialized when the iface is connected to its node
37 # These get initialized when the iface is connected to the internet
38 self.has_internet = False
41 return "%s<ip:%s/%s up mac:%s>" % (
42 self.__class__.__name__,
43 self.address, self.netmask,
49 def add_address(self, address, netprefix, broadcast):
50 raise RuntimeError, "Cannot add explicit addresses to public interface"
52 def pick_iface(self, siblings):
54 Picks an interface using the PLCAPI to query information about the node.
56 Needs an assigned node.
59 siblings: other NodeIface elements attached to the same node
62 if self.node is None or self.node._node_id is None:
63 raise RuntimeError, "Cannot pick interface without an assigned node"
65 avail = self._api.GetInterfaces(
66 node_id=self.node._node_id,
67 is_primary=self.primary,
68 fields=('interface_id','mac','netmask','ip') )
70 used = set([sibling._interface_id for sibling in siblings
71 if sibling._interface_id is not None])
73 for candidate in avail:
74 candidate_id = candidate['interface_id']
75 if candidate_id not in used:
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
84 raise RuntimeError, "Cannot configure interface: cannot find suitable interface in PlanetLab node"
87 if not self.has_internet:
88 raise RuntimeError, "All external interface devices must be connected to the Internet"
91 class _CrossIface(object):
92 def __init__(self, proto, addr, port, cipher):
93 self.tun_proto = proto
96 self.tun_cipher = cipher
98 # Cannot access cross peers
99 self.peer_proto_impl = None
103 self.__class__.__name__,
112 class TunIface(object):
113 _PROTO_MAP = tunproto.TUN_PROTO_MAP
116 def __init__(self, api=None):
118 api = plcapi.PLCAPI()
123 self.netprefix = None
127 self.device_name = None
130 self.txqueuelen = None
131 self.pointopoint = None
136 # These get initialized when the iface is connected to its node
139 # These get initialized when the iface is connected to any filter
140 self.filter_module = None
142 # These get initialized when the iface is configured
143 self.external_iface = None
145 # These get initialized when the iface is configured
146 # They're part of the TUN standard attribute set
149 self.tun_cipher = "AES"
151 # These get initialized when the iface is connected to its peer
152 self.peer_iface = None
153 self.peer_proto = None
154 self.peer_addr = None
155 self.peer_port = None
156 self.peer_proto_impl = None
157 self._delay_recover = False
159 # same as peer proto, but for execute-time standard attribute lookups
160 self.tun_proto = None
163 # Generate an initial random cryptographic key to use for tunnelling
164 # Upon connection, both endpoints will agree on a common one based on
166 self.tun_key = ( ''.join(map(chr, [
169 for r in (random.SystemRandom(),) ])
170 ).encode("base64").strip() )
174 return "%s<ip:%s/%s %s%s%s>" % (
175 self.__class__.__name__,
176 self.address, self.netprefix,
177 " up" if self.up else " down",
178 " snat" if self.snat else "",
179 (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
186 if self.peer_proto_impl:
187 return self.peer_proto_impl.if_name
189 def routes_here(self, route):
191 Returns True if the route should be attached to this interface
192 (ie, it references a gateway in this interface's network segment)
194 if self.address and self.netprefix:
195 addr, prefix = self.address, self.netprefix
196 pointopoint = self.pointopoint
198 pointopoint = self.peer_iface.address
203 dest, destprefix, nexthop, metric = route
205 myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
206 gwIp = ipaddr.IPNetwork(nexthop)
209 peerIp = ipaddr.IPNetwork(pointopoint)
218 def add_address(self, address, netprefix, broadcast):
219 if (self.address or self.netprefix or self.netmask) is not None:
220 raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
222 raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
224 self.address = address
225 self.netprefix = netprefix
226 self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
230 raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
231 if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
232 raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
233 if not self.address or not self.netprefix or not self.netmask:
234 raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
235 if self.filter_module and self.peer_proto not in ('udp','tcp',None):
236 raise RuntimeError, "Miscofnigured TUN: %s - filtered tunnels only work with udp or tcp links" % (self,)
237 if self.tun_cipher != 'PLAIN' and self.peer_proto not in ('udp','tcp',None):
238 raise RuntimeError, "Miscofnigured TUN: %s - ciphered tunnels only work with udp or tcp links" % (self,)
240 def _impl_instance(self, home_path, listening):
241 impl = self._PROTO_MAP[self.peer_proto](
242 self, self.peer_iface, home_path, self.tun_key, listening)
243 impl.port = self.tun_port
248 self.peer_proto_impl = self._impl_instance(
250 False) # no way to know, no need to know
251 self.peer_proto_impl.recover()
253 self._delay_recover = True
255 def prepare(self, home_path, listening):
256 if not self.peer_iface and (self.peer_proto and (listening or (self.peer_addr and self.peer_port))):
258 self.peer_iface = _CrossIface(
264 if not self.peer_proto_impl:
265 self.peer_proto_impl = self._impl_instance(home_path, listening)
266 if self._delay_recover:
267 self.peer_proto_impl.recover()
269 self.peer_proto_impl.prepare()
272 if self.peer_proto_impl:
273 self.peer_proto_impl.setup()
276 if self.peer_proto_impl:
277 self.peer_proto_impl.shutdown()
280 if self.peer_proto_impl:
281 self.peer_proto_impl.destroy()
282 self.peer_proto_impl = None
284 def async_launch_wait(self):
285 if self.peer_proto_impl:
286 self.peer_proto_impl.async_launch_wait()
288 def sync_trace(self, local_dir, whichtrace):
289 if self.peer_proto_impl:
290 return self.peer_proto_impl.sync_trace(local_dir, whichtrace)
294 def remote_trace_path(self, whichtrace):
295 if self.peer_proto_impl:
296 return self.peer_proto_impl.remote_trace_path(whichtrace)
300 class TapIface(TunIface):
301 _PROTO_MAP = tunproto.TAP_PROTO_MAP
304 # Yep, it does nothing - yet
305 class Internet(object):
306 def __init__(self, api=None):
308 api = plcapi.PLCAPI()
311 class NetPipe(object):
312 def __init__(self, api=None):
314 api = plcapi.PLCAPI()
330 # These get initialized when the pipe is connected to its node
332 self.configured = False
336 raise RuntimeError, "Undefined NetPipe mode"
337 if not self.portList:
338 raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
339 if not (self.plrIn or self.bwIn or self.delayIn):
340 raise RuntimeError, "Undefined NetPipe inbound characteristics"
341 if not (self.plrOut or self.bwOut or self.delayOut):
342 raise RuntimeError, "Undefined NetPipe outbound characteristics"
344 raise RuntimeError, "Unconnected NetPipe"
346 def _add_pipedef(self, bw, plr, delay, options):
348 options.extend(("delay","%dms" % (delay,)))
350 options.extend(("bw","%.8fMbit/s" % (bw,)))
352 options.extend(("plr","%.8f" % (plr,)))
354 def _get_ruledef(self):
357 "@" if self.addrList else "",
362 if self.bwIn or self.plrIn or self.delayIn:
364 self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
365 if self.bwOut or self.plrOut or self.delayOut:
366 options.append("OUT")
367 self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
368 options = ' '.join(options)
370 return (scope,options)
373 # Rules are safe on their nodes
374 self.configured = True
378 scope, options = self._get_ruledef()
379 command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
381 (out,err),proc = server.popen_ssh_command(
383 host = self.node.hostname,
385 user = self.node.slicename,
387 ident_key = self.node.ident_path,
388 server_key = self.node.server_key
392 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
394 # we have to clean up afterwards
395 self.configured = True
400 scope, options = self._get_ruledef()
401 command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
403 (out,err),proc = server.popen_ssh_command(
405 host = self.node.hostname,
407 user = self.node.slicename,
409 ident_key = self.node.ident_path,
410 server_key = self.node.server_key
414 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
419 scope, options = self._get_ruledef()
420 command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
422 (out,err),proc = server.popen_ssh_command(
424 host = self.node.hostname,
426 user = self.node.slicename,
428 ident_key = self.node.ident_path,
429 server_key = self.node.server_key
433 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
435 self.configured = False
437 def sync_trace(self, local_dir, whichtrace):
438 if whichtrace != 'netpipeStats':
439 raise ValueError, "Unsupported trace %s" % (whichtrace,)
441 local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
443 # create parent local folders
444 proc = subprocess.Popen(
445 ["mkdir", "-p", os.path.dirname(local_path)],
446 stdout = open("/dev/null","w"),
447 stdin = open("/dev/null","r"))
450 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
452 (out,err),proc = server.popen_ssh_command(
453 "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
454 host = self.node.hostname,
456 user = self.node.slicename,
458 ident_key = self.node.ident_path,
459 server_key = self.node.server_key
463 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
465 # dump results to file
466 f = open(local_path, "wb")
473 class TunFilter(object):
474 def __init__(self, api=None):
476 api = plcapi.PLCAPI()
482 # These get initialised when the filter is connected
483 self.peer_guid = None
484 self.peer_proto = None
485 self.iface_guid = None
489 def _get(what, self):
494 return getattr(wref, what)
498 def _set(what, self, val):
503 setattr(wref, what, val)
505 tun_proto = property(
506 functools.partial(_get, 'tun_proto'),
507 functools.partial(_set, 'tun_proto') )
509 functools.partial(_get, 'tun_addr'),
510 functools.partial(_set, 'tun_addr') )
512 functools.partial(_get, 'tun_port'),
513 functools.partial(_set, 'tun_port') )
515 functools.partial(_get, 'tun_key'),
516 functools.partial(_set, 'tun_key') )
517 tun_cipher = property(
518 functools.partial(_get, 'tun_cipher'),
519 functools.partial(_set, 'tun_cipher') )