2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
20 from nepi.execution.attribute import Attribute, Flags, Types
21 from nepi.execution.resource import clsinit_copy, ResourceState
22 from nepi.resources.linux.application import LinuxApplication
23 from nepi.resources.linux.node import LinuxNode
24 from nepi.util.timefuncs import tnow, tdiffsec
29 PYTHON_VSYS_VERSION = "1.0"
32 class LinuxTap(LinuxApplication):
34 _help = "Creates a TAP device on a Linux host"
41 def _register_attributes(cls):
42 ip = Attribute("ip", "IPv4 Address",
45 mac = Attribute("mac", "MAC Address",
48 prefix = Attribute("prefix", "IPv4 network prefix",
51 mtu = Attribute("mtu", "Maximum transmition unit for device",
54 devname = Attribute("deviceName",
55 "Name of the network interface (e.g. eth0, wlan0, etc)",
56 flags = Flags.NoWrite)
58 up = Attribute("up", "Link up",
61 pointopoint = Attribute("pointopoint", "Peer IP address",
64 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
67 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
70 gre_key = Attribute("greKey",
71 "GRE key to be used to configure GRE tunnel",
75 gre_remote = Attribute("greRemote",
76 "Public IP of remote endpoint for GRE tunnel",
79 pi = Attribute("pi", "Add PI (protocol information) header",
83 tear_down = Attribute("tearDown",
84 "Bash script to be executed before releasing the resource",
87 cls._register_attribute(ip)
88 cls._register_attribute(mac)
89 cls._register_attribute(prefix)
90 cls._register_attribute(mtu)
91 cls._register_attribute(devname)
92 cls._register_attribute(up)
93 cls._register_attribute(pointopoint)
94 cls._register_attribute(txqueuelen)
95 cls._register_attribute(gre_key)
96 cls._register_attribute(gre_remote)
97 cls._register_attribute(pi)
98 cls._register_attribute(tear_down)
100 def __init__(self, ec, guid):
101 super(LinuxTap, self).__init__(ec, guid)
102 self._home = "tap-%s" % self.guid
103 self._gre_enabled = False
104 self._tunnel_mode = False
108 node = self.get_connected(LinuxNode.get_rtype())
109 if node: return node[0]
110 raise RuntimeError, "linux::TAP/TUN devices must be connected to a linux::Node"
113 def gre_enabled(self):
114 if not self._gre_enabled:
115 from nepi.resources.linux.gretunnel import LinuxGRETunnel
116 gre = self.get_connected(LinuxGRETunnel.get_rtype())
117 if gre: self._gre_enabled = True
119 return self._gre_enabled
122 def tunnel_mode(self):
123 if not self._tunnel_mode:
124 from nepi.resources.linux.tunnel import LinuxTunnel
125 tunnel = self.get_connected(LinuxTunnel.get_rtype())
126 if tunnel: self._tunnel_mode = True
128 return self._tunnel_mode
130 def upload_sources(self):
133 # udp-connect python script
134 udp_connect = os.path.join(os.path.dirname(__file__), "scripts",
135 "linux-udp-connect.py")
137 scripts.append(udp_connect)
139 # tunnel creation python script
140 tunchannel = os.path.join(os.path.dirname(__file__), "scripts",
143 scripts.append(tunchannel)
146 scripts = ";".join(scripts)
148 self.node.upload(scripts,
149 os.path.join(self.node.src_dir),
152 # upload stop.sh script
153 stop_command = self.replace_paths(self._stop_command)
155 self.node.upload(stop_command,
156 os.path.join(self.app_home, "stop.sh"),
158 # Overwrite file every time.
159 # The stop.sh has the path to the socket, which should change
160 # on every experiment run.
163 def upload_start_command(self):
164 # If GRE mode is enabled, TAP creation is delayed until the
165 # tunnel is established
166 if not self.tunnel_mode:
167 # We want to make sure the device is up and running
168 # before the deploy is over, so we execute the
169 # start script now and wait until it finishes.
170 command = self.get("command")
171 command = self.replace_paths(command)
173 shfile = os.path.join(self.app_home, "start.sh")
174 self.node.run_and_wait(command, self.run_home,
179 if not self.node or self.node.state < ResourceState.PROVISIONED:
180 self.ec.schedule(self.reschedule_delay, self.deploy)
182 if not self.get("deviceName"):
183 self.set("deviceName", "%s%d" % (self.vif_prefix, self.guid))
185 if not self.get("command"):
186 self.set("command", self._start_command)
194 if self.state == ResourceState.READY:
195 command = self.get("command")
196 self.info("Starting command '%s'" % command)
200 msg = " Failed to execute command '%s'" % command
201 self.error(msg, out, err)
202 raise RuntimeError, msg
205 command = self.get('command') or ''
207 if self.state == ResourceState.STARTED:
208 self.info("Stopping command '%s'" % command)
210 command = "bash %s" % os.path.join(self.app_home, "stop.sh")
211 (out, err), proc = self.execute_command(command,
215 msg = " Failed to stop command '%s' " % command
216 self.error(msg, out, err)
222 state_check_delay = 0.5
223 if self._state == ResourceState.STARTED and \
224 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
226 if self.get("deviceName"):
227 (out, err), proc = self.node.execute("ip a")
229 if out.strip().find(self.get("deviceName")) == -1:
230 # tap is not running is not running (socket not found)
233 self._last_state_check = tnow()
237 def do_release(self):
238 # Node needs to wait until all associated RMs are released
240 from nepi.resources.linux.tunnel import LinuxTunnel
241 rms = self.get_connected(LinuxTunnel.get_rtype())
244 if rm.state < ResourceState.STOPPED:
245 self.ec.schedule(self.reschedule_delay, self.release)
248 super(LinuxTap, self).do_release()
250 def gre_connect(self, remote_endpoint, connection_app_home,
251 connection_run_home):
252 gre_connect_command = self._gre_connect_command(
253 remote_endpoint, connection_run_home)
255 # upload command to connect.sh script
256 shfile = os.path.join(connection_app_home, "gre-connect.sh")
257 self.node.upload_command(gre_connect_command,
261 # invoke connect script
262 cmd = "bash %s" % shfile
263 (out, err), proc = self.node.run(cmd, connection_run_home)
265 # check if execution errors occurred
266 msg = " Failed to connect endpoints "
268 if proc.poll() or err:
269 self.error(msg, out, err)
270 raise RuntimeError, msg
272 # Wait for pid file to be generated
273 pid, ppid = self.node.wait_pid(connection_run_home)
275 # If the process is not running, check for error information
276 # on the remote machine
277 if not pid or not ppid:
278 (out, err), proc = self.node.check_errors(connection_run_home)
279 # Out is what was written in the stderr file
281 msg = " Failed to start command '%s' " % command
282 self.error(msg, out, err)
283 raise RuntimeError, msg
287 def initiate_udp_connection(self, remote_endpoint, connection_app_home,
288 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
289 port = self.udp_connect(remote_endpoint, connection_app_home,
290 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
293 def udp_connect(self, remote_endpoint, connection_app_home,
294 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
295 udp_connect_command = self._udp_connect_command(
296 remote_endpoint, connection_run_home,
297 cipher, cipher_key, bwlimit, txqueuelen)
299 # upload command to connect.sh script
300 shfile = os.path.join(self.app_home, "udp-connect.sh")
301 self.node.upload_command(udp_connect_command,
305 # invoke connect script
306 cmd = "bash %s" % shfile
307 (out, err), proc = self.node.run(cmd, self.run_home)
309 # check if execution errors occurred
310 msg = "Failed to connect endpoints "
313 self.error(msg, out, err)
314 raise RuntimeError, msg
316 # Wait for pid file to be generated
317 self._pid, self._ppid = self.node.wait_pid(self.run_home)
319 # If the process is not running, check for error information
320 # on the remote machine
321 if not self._pid or not self._ppid:
322 (out, err), proc = self.node.check_errors(self.run_home)
323 # Out is what was written in the stderr file
325 msg = " Failed to start command '%s' " % command
326 self.error(msg, out, err)
327 raise RuntimeError, msg
329 port = self.wait_local_port()
333 def _udp_connect_command(self, remote_endpoint, connection_run_home,
334 cipher, cipher_key, bwlimit, txqueuelen):
336 # Set the remote endpoint to the IP of the device
337 self.set("pointopoint", remote_endpoint.get("ip"))
339 # Planetlab TAPs always use PI headers
340 from nepi.resources.planetlab.tap import PlanetlabTap
341 if self.is_rm_instance(PlanetlabTap.get_rtype()):
344 # Public IP of the remote NODE to stablish tunnel
345 remote_ip = remote_endpoint.node.get("ip")
347 local_port_file = os.path.join(self.run_home,
350 remote_port_file = os.path.join(self.run_home,
353 ret_file = os.path.join(self.run_home,
356 # Generate UDP connect command
357 # Use the start command to configure TAP with peer info
358 start_command = self._start_command
361 command.append(start_command)
363 # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
364 command.append(") & (")
365 command.append("sudo -S")
366 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
367 command.append("python ${SRC}/linux-udp-connect.py")
368 command.append("-N %s" % self.get("deviceName"))
369 command.append("-t %s" % self.vif_type)
372 command.append("-l %s " % local_port_file)
373 command.append("-r %s " % remote_port_file)
374 command.append("-H %s " % remote_ip)
375 command.append("-R %s " % ret_file)
377 command.append("-c %s " % cipher)
379 command.append("-k %s " % cipher_key)
381 command.append("-q %s " % txqueuelen)
383 command.append("-b %s " % bwlimit)
387 command = " ".join(command)
388 command = self.replace_paths(command)
392 def _gre_connect_command(self, remote_endpoint, connection_run_home):
393 # Set the remote endpoint to (private) device IP
394 self.set("pointopoint", remote_endpoint.get("ip"))
396 self.set("greRemote", remote_endpoint.node.get("ip"))
398 # Generate GRE connect command
400 command.append(self._stop_command)
401 command.append(") ; (")
402 command.append(self._start_gre_command)
405 command = " ".join(command)
406 command = self.replace_paths(command)
410 def establish_udp_connection(self, remote_endpoint, port):
411 # upload remote port number to file
412 rem_port = "%s\n" % port
413 self.node.upload(rem_port,
414 os.path.join(self.run_home, "remote_port"),
418 def verify_connection(self):
421 def terminate_connection(self):
422 if self._pid and self._ppid:
423 (out, err), proc = self.node.kill(self._pid, self._ppid,
426 # check if execution errors occurred
427 if proc.poll() and err:
428 msg = " Failed to Kill the Tap"
429 self.error(msg, out, err)
430 raise RuntimeError, msg
432 def check_status(self):
433 return self.node.status(self._pid, self._ppid)
435 def wait_local_port(self):
436 """ Waits until the local_port file for the endpoint is generated,
437 and returns the port number
440 return self.wait_file("local_port")
442 def wait_result(self):
443 """ Waits until the return code file for the endpoint is generated
446 return self.wait_file("ret_file")
448 def wait_file(self, filename):
449 """ Waits until file on endpoint is generated """
454 (out, err), proc = self.node.check_output(
455 self.run_home, filename)
463 msg = "Couldn't retrieve %s" % filename
464 self.error(msg, out, err)
465 raise RuntimeError, msg
470 def _start_command(self):
472 if not self.gre_enabled:
473 # Make sure to clean TAP if it existed
474 stop_command = self._stop_command
477 start_command.append("sudo -S ip tuntap add %s mode %s %s" % (
478 self.get("deviceName"),
480 "pi" if self.get("pi") else ""))
481 start_command.append("sudo -S ip link set %s up" % self.get("deviceName"))
482 start_command.append("sudo -S ip addr add %s/%s dev %s" % (
485 self.get("deviceName"),
488 start_command = ";".join(start_command)
491 command.append(stop_command)
492 command.append(") ; (")
493 command.append(start_command)
496 return " ".join(command)
499 def _stop_command(self):
501 command.append("sudo -S ip link set %s down" % self.get("deviceName"))
502 command.append("sudo -S ip link del %s" % self.get("deviceName"))
504 return ";".join(command)
507 def _start_gre_command(self):
509 command.append("sudo -S modprobe ip_gre")
510 command.append("sudo -S ip link add %s type gre remote %s local %s ttl 64 csum key %s" % (
511 self.get("deviceName"),
512 self.get("greRemote"),
516 command.append("sudo -S ip addr add %s/%s peer %s/%s dev %s" % (
519 self.get("pointopoint"),
521 self.get("deviceName"),
523 command.append("sudo -S ip link set %s up " % self.get("deviceName"))
525 return ";".join(command)
532 def vif_type_flag(self):
533 return LinuxTap.IFF_TAP
536 def vif_prefix(self):
540 return os.path.join(self.run_home, "tap.sock")
542 def valid_connection(self, guid):