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 endpoint_ip = Attribute("endpoint_ip", "IPv4 Address",
45 mac = Attribute("mac", "MAC Address",
48 endpoint_prefix = Attribute("endpoint_prefix", "IPv4 network prefix",
52 mtu = Attribute("mtu", "Maximum transmition unit for device",
55 devname = Attribute("deviceName",
56 "Name of the network interface (e.g. eth0, wlan0, etc)",
57 flags = Flags.NoWrite)
59 up = Attribute("up", "Link up",
62 pointopoint = Attribute("pointopoint", "Peer IP address",
65 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
68 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
71 gre_key = Attribute("greKey",
72 "GRE key to be used to configure GRE tunnel",
76 gre_remote = Attribute("greRemote",
77 "Public IP of remote endpoint for GRE tunnel",
80 pi = Attribute("pi", "Add PI (protocol information) header",
84 tear_down = Attribute("tearDown",
85 "Bash script to be executed before releasing the resource",
88 cls._register_attribute(endpoint_ip)
89 cls._register_attribute(mac)
90 cls._register_attribute(endpoint_prefix)
91 cls._register_attribute(mtu)
92 cls._register_attribute(devname)
93 cls._register_attribute(up)
94 cls._register_attribute(pointopoint)
95 cls._register_attribute(txqueuelen)
96 cls._register_attribute(gre_key)
97 cls._register_attribute(gre_remote)
98 cls._register_attribute(pi)
99 cls._register_attribute(tear_down)
101 def __init__(self, ec, guid):
102 super(LinuxTap, self).__init__(ec, guid)
103 self._home = "tap-%s" % self.guid
104 self._gre_enabled = False
105 self._tunnel_mode = False
109 node = self.get_connected(LinuxNode.get_rtype())
110 if node: return node[0]
111 raise RuntimeError, "linux::TAP/TUN devices must be connected to a linux::Node"
114 def gre_enabled(self):
115 if not self._gre_enabled:
116 from nepi.resources.linux.gretunnel import LinuxGRETunnel
117 gre = self.get_connected(LinuxGRETunnel.get_rtype())
118 if gre: self._gre_enabled = True
120 return self._gre_enabled
123 def tunnel_mode(self):
124 if not self._tunnel_mode:
125 from nepi.resources.linux.tunnel import LinuxTunnel
126 tunnel = self.get_connected(LinuxTunnel.get_rtype())
127 if tunnel: self._tunnel_mode = True
129 return self._tunnel_mode
131 def upload_sources(self):
134 # udp-connect python script
135 udp_connect = os.path.join(os.path.dirname(__file__), "scripts",
136 "linux-udp-connect.py")
138 scripts.append(udp_connect)
140 # tunnel creation python script
141 tunchannel = os.path.join(os.path.dirname(__file__), "scripts",
144 scripts.append(tunchannel)
147 scripts = ";".join(scripts)
149 self.node.upload(scripts,
150 os.path.join(self.node.src_dir),
153 # upload stop.sh script
154 stop_command = self.replace_paths(self._stop_command)
156 self.node.upload(stop_command,
157 os.path.join(self.app_home, "stop.sh"),
159 # Overwrite file every time.
160 # The stop.sh has the path to the socket, which should change
161 # on every experiment run.
164 def upload_start_command(self):
165 # If GRE mode is enabled, TAP creation is delayed until the
166 # tunnel is established
167 if not self.tunnel_mode:
168 # We want to make sure the device is up and running
169 # before the deploy is over, so we execute the
170 # start script now and wait until it finishes.
171 command = self.get("command")
172 command = self.replace_paths(command)
174 shfile = os.path.join(self.app_home, "start.sh")
175 self.node.run_and_wait(command, self.run_home,
180 if not self.node or self.node.state < ResourceState.PROVISIONED:
181 self.ec.schedule(self.reschedule_delay, self.deploy)
183 if not self.get("deviceName"):
184 self.set("deviceName", "%s%d" % (self.vif_prefix, self.guid))
186 if not self.get("command"):
187 self.set("command", self._start_command)
195 if self.state == ResourceState.READY:
196 command = self.get("command")
197 self.info("Starting command '%s'" % command)
201 msg = " Failed to execute command '%s'" % command
202 self.error(msg, out, err)
203 raise RuntimeError, msg
206 command = self.get('command') or ''
208 if self.state == ResourceState.STARTED:
209 self.info("Stopping command '%s'" % command)
211 command = "bash %s" % os.path.join(self.app_home, "stop.sh")
212 (out, err), proc = self.execute_command(command,
216 msg = " Failed to stop command '%s' " % command
217 self.error(msg, out, err)
223 state_check_delay = 0.5
224 if self._state == ResourceState.STARTED and \
225 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
227 if self.get("deviceName"):
228 (out, err), proc = self.node.execute("ip a")
230 if out.strip().find(self.get("deviceName")) == -1:
231 # tap is not running is not running (socket not found)
234 self._last_state_check = tnow()
238 def do_release(self):
239 # Node needs to wait until all associated RMs are released
241 from nepi.resources.linux.tunnel import LinuxTunnel
242 rms = self.get_connected(LinuxTunnel.get_rtype())
245 if rm.state < ResourceState.STOPPED:
246 self.ec.schedule(self.reschedule_delay, self.release)
249 super(LinuxTap, self).do_release()
251 def gre_connect(self, remote_endpoint, connection_app_home,
252 connection_run_home):
253 gre_connect_command = self._gre_connect_command(
254 remote_endpoint, connection_run_home)
256 # upload command to connect.sh script
257 shfile = os.path.join(connection_app_home, "gre-connect.sh")
258 self.node.upload_command(gre_connect_command,
262 # invoke connect script
263 cmd = "bash %s" % shfile
264 (out, err), proc = self.node.run(cmd, connection_run_home)
266 # check if execution errors occurred
267 msg = " Failed to connect endpoints "
269 if proc.poll() or err:
270 self.error(msg, out, err)
271 raise RuntimeError, msg
273 # Wait for pid file to be generated
274 pid, ppid = self.node.wait_pid(connection_run_home)
276 # If the process is not running, check for error information
277 # on the remote machine
278 if not pid or not ppid:
279 (out, err), proc = self.node.check_errors(connection_run_home)
280 # Out is what was written in the stderr file
282 msg = " Failed to start command '%s' " % command
283 self.error(msg, out, err)
284 raise RuntimeError, msg
288 def initiate_udp_connection(self, remote_endpoint, connection_app_home,
289 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
290 port = self.udp_connect(remote_endpoint, connection_app_home,
291 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
294 def udp_connect(self, remote_endpoint, connection_app_home,
295 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
296 udp_connect_command = self._udp_connect_command(
297 remote_endpoint, connection_run_home,
298 cipher, cipher_key, bwlimit, txqueuelen)
300 # upload command to connect.sh script
301 shfile = os.path.join(self.app_home, "udp-connect.sh")
302 self.node.upload_command(udp_connect_command,
306 # invoke connect script
307 cmd = "bash %s" % shfile
308 (out, err), proc = self.node.run(cmd, self.run_home)
310 # check if execution errors occurred
311 msg = "Failed to connect endpoints "
314 self.error(msg, out, err)
315 raise RuntimeError, msg
317 # Wait for pid file to be generated
318 self._pid, self._ppid = self.node.wait_pid(self.run_home)
320 # If the process is not running, check for error information
321 # on the remote machine
322 if not self._pid or not self._ppid:
323 (out, err), proc = self.node.check_errors(self.run_home)
324 # Out is what was written in the stderr file
326 msg = " Failed to start command '%s' " % command
327 self.error(msg, out, err)
328 raise RuntimeError, msg
330 port = self.wait_local_port()
334 def _udp_connect_command(self, remote_endpoint, connection_run_home,
335 cipher, cipher_key, bwlimit, txqueuelen):
337 # Set the remote endpoint
338 self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
340 # Planetlab TAPs always use PI headers
341 from nepi.resources.planetlab.tap import PlanetlabTap
342 if self.is_rm_instance(PlanetlabTap.get_rtype()):
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
394 self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
395 self.set("greRemote", remote_endpoint.node.get("ip"))
397 # Generate GRE connect command
399 command.append(self._stop_command)
400 command.append(") ; (")
401 command.append(self._start_gre_command)
404 command = " ".join(command)
405 command = self.replace_paths(command)
409 def establish_udp_connection(self, remote_endpoint, port):
410 # upload remote port number to file
411 rem_port = "%s\n" % port
412 self.node.upload(rem_port,
413 os.path.join(self.run_home, "remote_port"),
417 def verify_connection(self):
420 def terminate_connection(self):
421 if self._pid and self._ppid:
422 (out, err), proc = self.node.kill(self._pid, self._ppid,
425 # check if execution errors occurred
426 if proc.poll() and err:
427 msg = " Failed to Kill the Tap"
428 self.error(msg, out, err)
429 raise RuntimeError, msg
431 def check_status(self):
432 return self.node.status(self._pid, self._ppid)
434 def wait_local_port(self):
435 """ Waits until the local_port file for the endpoint is generated,
436 and returns the port number
439 return self.wait_file("local_port")
441 def wait_result(self):
442 """ Waits until the return code file for the endpoint is generated
445 return self.wait_file("ret_file")
447 def wait_file(self, filename):
448 """ Waits until file on endpoint is generated """
453 (out, err), proc = self.node.check_output(
454 self.run_home, filename)
462 msg = "Couldn't retrieve %s" % filename
463 self.error(msg, out, err)
464 raise RuntimeError, msg
469 def _start_command(self):
471 if not self.gre_enabled:
472 # Make sure to clean TAP if it existed
473 stop_command = self._stop_command
476 start_command.append("sudo -S ip tuntap add %s mode %s %s" % (
477 self.get("deviceName"),
479 "pi" if self.get("pi") else ""))
480 start_command.append("sudo -S ip link set %s up" % self.get("deviceName"))
481 start_command.append("sudo -S ip addr add %s/%d dev %s" % (
482 self.get("endpoint_ip"),
483 self.get("endpoint_prefix"),
484 self.get("deviceName"),
487 start_command = ";".join(start_command)
490 command.append(stop_command)
491 command.append(") ; (")
492 command.append(start_command)
495 return " ".join(command)
498 def _stop_command(self):
500 command.append("sudo -S ip link set %s down" % self.get("deviceName"))
501 command.append("sudo -S ip link del %s" % self.get("deviceName"))
503 return ";".join(command)
506 def _start_gre_command(self):
508 command.append("sudo -S modprobe ip_gre")
509 command.append("sudo -S ip link add %s type gre remote %s local %s ttl 64 csum key %s" % (
510 self.get("deviceName"),
511 self.get("greRemote"),
515 command.append("sudo -S ip addr add %s/%d peer %s/%d dev %s" % (
516 self.get("endpoint_ip"),
517 self.get("endpoint_prefix"),
518 self.get("pointopoint"),
519 self.get("endpoint_prefix"),
520 self.get("deviceName"),
522 command.append("sudo -S ip link set %s up " % self.get("deviceName"))
524 return ";".join(command)
531 def vif_type_flag(self):
532 return LinuxTap.IFF_TAP
535 def vif_prefix(self):
539 return os.path.join(self.run_home, "tap.sock")
541 def valid_connection(self, guid):