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 version 2 as
7 # published by the Free Software Foundation;
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19 from nepi.execution.attribute import Attribute, Flags, Types
20 from nepi.execution.resource import clsinit_copy, ResourceState
21 from nepi.resources.linux.application import LinuxApplication
22 from nepi.resources.linux.node import LinuxNode
23 from nepi.util.timefuncs import tnow, tdiffsec
28 PYTHON_VSYS_VERSION = "1.0"
31 class LinuxTap(LinuxApplication):
33 _help = "Creates a TAP device on a Linux host"
39 def _register_attributes(cls):
40 ip = Attribute("ip", "IPv4 Address",
43 mac = Attribute("mac", "MAC Address",
46 prefix = Attribute("prefix", "IPv4 network prefix",
49 mtu = Attribute("mtu", "Maximum transmition unit for device",
52 devname = Attribute("deviceName",
53 "Name of the network interface (e.g. eth0, wlan0, etc)",
54 flags = Flags.NoWrite)
56 up = Attribute("up", "Link up", default=True,
59 pointopoint = Attribute("pointopoint", "Peer IP address",
62 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
65 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
68 gre_key = Attribute("greKey",
69 "GRE key to be used to configure GRE tunnel",
73 gre_remote = Attribute("greRemote",
74 "Public IP of remote endpoint for GRE tunnel",
77 pi = Attribute("pi", "Add PI (protocol information) header",
81 tear_down = Attribute("tearDown",
82 "Bash script to be executed before releasing the resource",
85 cls._register_attribute(ip)
86 cls._register_attribute(mac)
87 cls._register_attribute(prefix)
88 cls._register_attribute(mtu)
89 cls._register_attribute(devname)
90 cls._register_attribute(up)
91 cls._register_attribute(pointopoint)
92 cls._register_attribute(txqueuelen)
93 cls._register_attribute(gre_key)
94 cls._register_attribute(gre_remote)
95 cls._register_attribute(pi)
96 cls._register_attribute(tear_down)
98 def __init__(self, ec, guid):
99 super(LinuxTap, self).__init__(ec, guid)
100 self._gre_enabled = None
101 self._vif_prefix = "tap"
102 self._vif_type = "IFF_TAP"
103 self._vif_type_flag = LinuxTap.IFF_TAP
104 self._home = "%s-%s" % (self.vif_prefix, self.guid)
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 self._gre_enabled is None:
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
121 def upload_sources(self):
124 # udp-connect python script
125 udp_connect = os.path.join(os.path.dirname(__file__), "scripts",
126 "linux-udp-connect.py")
128 scripts.append(udp_connect)
130 tap_create = os.path.join(os.path.dirname(__file__), "scripts",
131 "linux-tap-create.py")
133 scripts.append(tap_create)
135 tap_delete = os.path.join(os.path.dirname(__file__), "scripts",
136 "linux-tap-delete.py")
138 scripts.append(tap_delete)
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.gre_enabled:
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,
179 def upload_start_command(self):
180 # If GRE mode is enabled, TAP creation is delayed until the
181 # tunnel is established
182 if not self.gre_enabled:
183 # Overwrite file every time.
184 # The start.sh has the path to the socket, wich should change
185 # on every experiment run.
186 command = self.get("command")
188 self.info("Uploading command '%s'" % command)
190 # replace application specific paths in the command
191 command = self.replace_paths(command)
193 # replace application specific paths in the environment
194 env = self.get("env")
195 env = env and self.replace_paths(env)
197 shfile = os.path.join(self.app_home, "start.sh")
199 self.node.upload_command(command,
204 # We want to make sure the device is up and running
205 # before the deploy finishes, so we execute now the
206 # start script. We run it in background, because the
207 # TAP will live for as long as the process that
208 # created it is running, and wait until the TAP
210 self._run_in_background()
213 if not self.node or self.node.state < ResourceState.PROVISIONED:
214 self.ec.schedule(self.reschedule_delay, self.deploy)
217 self._vif_prefix = "gre"
218 self._home = "%s-%s" % (self.vif_prefix, self.guid)
220 if not self.get("deviceName"):
221 self.set("deviceName", "%s%d" % (self.vif_prefix, self.guid))
223 if not self.get("command"):
224 self.set("command", self._start_command)
226 if not self.get("depends"):
227 self.set("depends", self._dependencies)
229 if not self.get("install"):
230 self.set("install", self._install)
238 if self.state == ResourceState.READY:
239 command = self.get("command")
240 self.info("Starting command '%s'" % command)
244 msg = " Failed to execute command '%s'" % command
245 self.error(msg, out, err)
246 raise RuntimeError, msg
249 command = self.get('command') or ''
251 if self.state == ResourceState.STARTED:
252 self.info("Stopping command '%s'" % command)
254 command = "bash %s" % os.path.join(self.app_home, "stop.sh")
255 (out, err), proc = self.execute_command(command,
259 msg = " Failed to stop command '%s' " % command
260 self.error(msg, out, err)
266 state_check_delay = 0.5
267 if self._state == ResourceState.STARTED and \
268 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
270 if self.get("deviceName"):
271 (out, err), proc = self.node.execute("ifconfig")
273 if out.strip().find(self.get("deviceName")) == -1:
274 # tap is not running is not running (socket not found)
277 self._last_state_check = tnow()
281 def do_release(self):
282 # Node needs to wait until all associated RMs are released
284 from nepi.resources.linux.tunnel import LinuxTunnel
285 rms = self.get_connected(LinuxTunnel.get_rtype())
288 if rm.state < ResourceState.STOPPED:
289 self.ec.schedule(self.reschedule_delay, self.release)
292 super(LinuxTap, self).do_release()
294 def gre_connect(self, remote_endpoint, connection_app_home,
295 connection_run_home):
296 gre_connect_command = self._gre_connect_command(remote_endpoint,
297 connection_app_home, connection_run_home)
299 # upload command to connect.sh script
300 shfile = os.path.join(connection_app_home, "gre-connect.sh")
301 self.node.upload_command(gre_connect_command,
305 # invoke connect script
306 cmd = "bash %s" % shfile
307 (out, err), proc = self.node.run(cmd, connection_run_home,
308 pidfile = "gre_connect_pidfile",
309 stdout = "gre_connect_stdout",
310 stderr = "gre_connect_stderr",
313 # check if execution errors occurred
314 msg = " Failed to connect endpoints "
316 if proc.poll() or err:
317 self.error(msg, out, err)
318 raise RuntimeError, msg
320 # Wait for pid file to be generated
321 pid, ppid = self.node.wait_pid(connection_run_home,
322 pidfile = "gre_connect_pidfile")
324 # If the process is not running, check for error information
325 # on the remote machine
326 if not pid or not ppid:
327 (out, err), proc = self.node.check_errors(connection_run_home,
328 stderr = "gre_connect_stderr")
330 # Out is what was written in the stderr file
332 msg = " Failed to start command '%s' " % command
333 self.error(msg, out, err)
334 raise RuntimeError, msg
338 def initiate_udp_connection(self, remote_endpoint, connection_app_home,
339 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
340 port = self.udp_connect(remote_endpoint, connection_app_home,
341 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
344 def udp_connect(self, remote_endpoint, connection_app_home,
345 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
346 udp_connect_command = self._udp_connect_command(
347 remote_endpoint, connection_app_home, connection_run_home,
348 cipher, cipher_key, bwlimit, txqueuelen)
350 # upload command to connect.sh script
351 shfile = os.path.join(connection_app_home, "udp-connect.sh")
352 self.node.upload_command(udp_connect_command,
356 # invoke connect script
357 cmd = "bash %s" % shfile
358 (out, err), proc = self.node.run(cmd, connection_run_home,
359 pidfile = "udp_connect_pidfile",
360 stdout = "udp_connect_stdout",
361 stderr = "udp_connect_stderr",
364 # check if execution errors occurred
365 msg = "Failed to connect endpoints "
368 self.error(msg, out, err)
369 raise RuntimeError, msg
371 # Wait for pid file to be generated
372 self._pid, self._ppid = self.node.wait_pid(
374 pidfile = "udp_connect_pidfile")
376 # If the process is not running, check for error information
377 # on the remote machine
378 if not self._pid or not self._ppid:
379 (out, err), proc = self.node.check_errors(
381 stderr = "udp_connect_stderr")
383 # Out is what was written in the stderr file
385 msg = " Failed to start command '%s' " % command
386 self.error(msg, out, err)
387 raise RuntimeError, msg
389 return self.wait_file(connection_run_home, "local_port")
391 def establish_udp_connection(self, remote_endpoint,
392 connection_app_home, connection_run_home, port):
393 # upload remote port number to file
394 rem_port = "%s\n" % port
395 self.node.upload(rem_port,
396 os.path.join(connection_run_home, "remote_port"),
400 def verify_connection(self, remote_endpoint,
401 connection_app_home, connection_run_home):
403 return self.wait_file(connection_run_home, "ret_file")
405 def terminate_connection(self, remote_endpoint,
406 connection_app_home, connection_run_home):
407 if self._pid and self._ppid:
408 (out, err), proc = self.node.kill(self._pid, self._ppid,
411 # check if execution errors occurred
412 if proc.poll() and err:
413 msg = " Failed to Kill the Tap"
414 self.error(msg, out, err)
415 raise RuntimeError, msg
417 def check_status(self):
418 return self.node.status(self._pid, self._ppid)
420 def wait_file(self, home, filename):
421 """ Waits until file on endpoint is generated """
426 (out, err), proc = self.node.check_output(home, filename)
434 msg = "Couldn't retrieve %s" % filename
435 self.error(msg, out, err)
436 raise RuntimeError, msg
441 def _start_command(self):
445 command = ["sudo -S "]
446 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
447 command.append("python ${SRC}/linux-tap-create.py")
448 command.append("-t %s" % self.vif_type)
449 command.append("-a %s" % self.get("ip"))
450 command.append("-n %s" % self.get("prefix"))
451 command.append("-N %s " % self.get("deviceName"))
452 command.append("-S %s " % self.sock_name)
456 return " ".join(command)
459 def _stop_command(self):
461 command = self._stop_gre_command
463 command = ["sudo -S "]
464 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
465 command.append("python ${SRC}/linux-tap-delete.py")
466 command.append("-N %s " % self.get("deviceName"))
467 command.append("-S %s " % self.sock_name)
468 command = " ".join(command)
472 def _gre_connect_command(self, remote_endpoint,
473 connection_app_home, connecrion_app_home):
474 # Set the remote endpoint to (private) device IP
475 self.set("pointopoint", remote_endpoint.get("ip"))
477 self.set("greRemote", remote_endpoint.node.get("ip"))
479 # Generate GRE connect command
481 command.append(self._stop_gre_command)
482 command.append(") ; (")
483 command.append(self._start_gre_command)
486 command = " ".join(command)
487 command = self.replace_paths(command)
492 def _start_gre_command(self):
494 command.append("sudo -S modprobe ip_gre")
495 command.append("sudo -S ip tunnel add %s mode gre remote %s local %s ttl 255 csum key %s" % (
496 self.get("deviceName"),
497 self.get("greRemote"),
501 command.append("sudo -S ip addr add %s/%s peer %s/%s dev %s" % (
504 self.get("pointopoint"),
506 self.get("deviceName"),
508 command.append("sudo -S ip link set %s up " % self.get("deviceName"))
510 return ";".join(command)
513 def _stop_gre_command(self):
515 command.append("sudo -S modprobe -r ip_gre")
516 command.append("sudo -S ip link set down dev %s" % (
517 self.get("deviceName"),
519 command.append("sudo -S ip link del dev %s" % (
520 self.get("deviceName"),
523 return ";".join(command)
525 def _udp_connect_command(self, remote_endpoint,
526 connection_app_home, connection_run_home,
527 cipher, cipher_key, bwlimit, txqueuelen):
529 # Set the remote endpoint to the IP of the device
530 self.set("pointopoint", remote_endpoint.get("ip"))
532 # Public IP of the remote NODE to stablish tunnel
533 remote_ip = remote_endpoint.node.get("ip")
534 local_ip = self.node.get("ip")
536 local_port_file = os.path.join(connection_run_home,
539 remote_port_file = os.path.join(connection_run_home,
542 ret_file = os.path.join(connection_run_home,
545 # Generate UDP connect command
546 # Use the start command to configure TAP with peer info
547 start_command = self._start_command
550 # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
551 command.append("sudo -S")
552 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
553 command.append("python ${SRC}/linux-udp-connect.py")
554 command.append("-t %s" % self.vif_type)
555 command.append("-S %s " % self.sock_name)
556 command.append("-p %s " % local_port_file)
557 command.append("-P %s " % remote_port_file)
558 command.append("-o %s " % local_ip)
559 command.append("-O %s " % remote_ip)
560 command.append("-R %s " % ret_file)
564 command.append("-c %s " % cipher)
566 command.append("-k %s " % cipher_key)
568 command.append("-q %s " % txqueuelen)
570 command.append("-b %s " % bwlimit)
572 command = " ".join(command)
573 command = self.replace_paths(command)
578 def _dependencies(self):
579 return "mercurial make gcc"
583 # Install python-vsys and python-passfd
584 install_passfd = ( " ( python -c 'import passfd' ) "
588 " hg clone http://nepi.inria.fr/code/python-passfd ; "
589 " cd python-passfd ; "
591 " sudo -S make install "
594 return install_passfd
596 def valid_connection(self, guid):
602 return self._vif_type
605 def vif_type_flag(self):
606 return self._vif_type_flag
609 def vif_prefix(self):
610 return self._vif_prefix
614 return os.path.join(self.run_home, "%s.sock" % self.vif_prefix)
616 def valid_connection(self, guid):