2 # -*- coding: utf-8 -*-
4 from constants import TESTBED_ID
5 import nepi.util.ipaddr2 as ipaddr2
6 import nepi.util.server as server
16 class NodeIface(object):
17 def __init__(self, api=None):
25 # These get initialized at configuration time
31 self._interface_id = None
33 # These get initialized when the iface is connected to its node
36 # These get initialized when the iface is connected to the internet
37 self.has_internet = False
40 return "%s<ip:%s/%s up mac:%s>" % (
41 self.__class__.__name__,
42 self.address, self.netmask,
48 def add_address(self, address, netprefix, broadcast):
49 raise RuntimeError, "Cannot add explicit addresses to public interface"
51 def pick_iface(self, siblings):
53 Picks an interface using the PLCAPI to query information about the node.
55 Needs an assigned node.
58 siblings: other NodeIface elements attached to the same node
61 if self.node is None or self.node._node_id is None:
62 raise RuntimeError, "Cannot pick interface without an assigned node"
64 avail = self._api.GetInterfaces(
65 node_id=self.node._node_id,
66 is_primary=self.primary,
67 fields=('interface_id','mac','netmask','ip') )
69 used = set([sibling._interface_id for sibling in siblings
70 if sibling._interface_id is not None])
72 for candidate in avail:
73 candidate_id = candidate['interface_id']
74 if candidate_id not in used:
76 self._interface_id = candidate_id
77 self.address = candidate['ip']
78 self.lladdr = candidate['mac']
79 self.netprefix = candidate['netmask']
80 self.netmask = ipaddr2.ipv4_dot2mask(self.netprefix) if self.netprefix else None
83 raise RuntimeError, "Cannot configure interface: cannot find suitable interface in PlanetLab node"
86 if not self.has_internet:
87 raise RuntimeError, "All external interface devices must be connected to the Internet"
90 class _CrossIface(object):
91 def __init__(self, proto, addr, port):
92 self.tun_proto = proto
96 # Cannot access cross peers
97 self.peer_proto_impl = None
101 self.__class__.__name__,
109 class TunIface(object):
110 _PROTO_MAP = tunproto.TUN_PROTO_MAP
113 def __init__(self, api=None):
115 api = plcapi.PLCAPI()
120 self.netprefix = None
124 self.device_name = None
127 self.txqueuelen = None
128 self.pointopoint = None
133 # These get initialized when the iface is connected to its node
136 # These get initialized when the iface is configured
137 self.external_iface = None
139 # These get initialized when the iface is configured
140 # They're part of the TUN standard attribute set
144 # These get initialized when the iface is connected to its peer
145 self.peer_iface = None
146 self.peer_proto = None
147 self.peer_addr = None
148 self.peer_port = None
149 self.peer_proto_impl = None
151 # same as peer proto, but for execute-time standard attribute lookups
152 self.tun_proto = None
155 # Generate an initial random cryptographic key to use for tunnelling
156 # Upon connection, both endpoints will agree on a common one based on
158 self.tun_key = ( ''.join(map(chr, [
161 for r in (random.SystemRandom(),) ])
162 ).encode("base64").strip() )
166 return "%s<ip:%s/%s %s%s%s>" % (
167 self.__class__.__name__,
168 self.address, self.netprefix,
169 " up" if self.up else " down",
170 " snat" if self.snat else "",
171 (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
178 if self.peer_proto_impl:
179 return self.peer_proto_impl.if_name
181 def routes_here(self, route):
183 Returns True if the route should be attached to this interface
184 (ie, it references a gateway in this interface's network segment)
186 if self.address and self.netprefix:
187 addr, prefix = self.address, self.netprefix
191 dest, destprefix, nexthop = route
193 myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
194 gwIp = ipaddr.IPNetwork(nexthop)
197 peerIp = ipaddr.IPNetwork(self.pointopoint)
206 def add_address(self, address, netprefix, broadcast):
207 if (self.address or self.netprefix or self.netmask) is not None:
208 raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
210 raise ValueError, "%s interfaces cannot broadcast in PlanetLab" % (self._KIND,)
212 self.address = address
213 self.netprefix = netprefix
214 self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
218 raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
219 if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
220 raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
221 if not self.address or not self.netprefix or not self.netmask:
222 raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
224 def _impl_instance(self, home_path, listening):
225 impl = self._PROTO_MAP[self.peer_proto](
226 self, self.peer_iface, home_path, self.tun_key, listening)
227 impl.port = self.tun_port
230 def prepare(self, home_path, listening):
231 if not self.peer_iface and (self.peer_proto and (listening or (self.peer_addr and self.peer_port))):
233 self.peer_iface = _CrossIface(
238 if not self.peer_proto_impl:
239 self.peer_proto_impl = self._impl_instance(home_path, listening)
240 self.peer_proto_impl.prepare()
243 if self.peer_proto_impl:
244 self.peer_proto_impl.setup()
247 if self.peer_proto_impl:
248 self.peer_proto_impl.shutdown()
251 if self.peer_proto_impl:
252 self.peer_proto_impl.destroy()
253 self.peer_proto_impl = None
255 def async_launch_wait(self):
256 if self.peer_proto_impl:
257 self.peer_proto_impl.async_launch_wait()
259 def sync_trace(self, local_dir, whichtrace):
260 if self.peer_proto_impl:
261 return self.peer_proto_impl.sync_trace(local_dir, whichtrace)
265 class TapIface(TunIface):
266 _PROTO_MAP = tunproto.TAP_PROTO_MAP
269 # Yep, it does nothing - yet
270 class Internet(object):
271 def __init__(self, api=None):
273 api = plcapi.PLCAPI()
276 class NetPipe(object):
277 def __init__(self, api=None):
279 api = plcapi.PLCAPI()
295 # These get initialized when the pipe is connected to its node
297 self.configured = False
301 raise RuntimeError, "Undefined NetPipe mode"
302 if not self.portList:
303 raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
304 if not (self.plrIn or self.bwIn or self.delayIn):
305 raise RuntimeError, "Undefined NetPipe inbound characteristics"
306 if not (self.plrOut or self.bwOut or self.delayOut):
307 raise RuntimeError, "Undefined NetPipe outbound characteristics"
309 raise RuntimeError, "Unconnected NetPipe"
311 def _add_pipedef(self, bw, plr, delay, options):
313 options.extend(("delay","%dms" % (delay,)))
315 options.extend(("bw","%.8fMbit/s" % (bw,)))
317 options.extend(("plr","%.8f" % (plr,)))
319 def _get_ruledef(self):
322 "@" if self.addrList else "",
327 if self.bwIn or self.plrIn or self.delayIn:
329 self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
330 if self.bwOut or self.plrOut or self.delayOut:
331 options.append("OUT")
332 self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
333 options = ' '.join(options)
335 return (scope,options)
339 scope, options = self._get_ruledef()
340 command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
342 (out,err),proc = server.popen_ssh_command(
344 host = self.node.hostname,
346 user = self.node.slicename,
348 ident_key = self.node.ident_path,
349 server_key = self.node.server_key
353 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
355 # we have to clean up afterwards
356 self.configured = True
361 scope, options = self._get_ruledef()
362 command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
364 (out,err),proc = server.popen_ssh_command(
366 host = self.node.hostname,
368 user = self.node.slicename,
370 ident_key = self.node.ident_path,
371 server_key = self.node.server_key
375 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
380 scope, options = self._get_ruledef()
381 command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
383 (out,err),proc = server.popen_ssh_command(
385 host = self.node.hostname,
387 user = self.node.slicename,
389 ident_key = self.node.ident_path,
390 server_key = self.node.server_key
394 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
396 self.configured = False
398 def sync_trace(self, local_dir, whichtrace):
399 if whichtrace != 'netpipeStats':
400 raise ValueError, "Unsupported trace %s" % (whichtrace,)
402 local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
404 # create parent local folders
405 proc = subprocess.Popen(
406 ["mkdir", "-p", os.path.dirname(local_path)],
407 stdout = open("/dev/null","w"),
408 stdin = open("/dev/null","r"))
411 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
413 (out,err),proc = server.popen_ssh_command(
414 "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
415 host = self.node.hostname,
417 user = self.node.slicename,
419 ident_key = self.node.ident_path,
420 server_key = self.node.server_key
424 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
426 # dump results to file
427 f = open(local_path, "wb")