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"
40 def _register_attributes(cls):
41 ip = Attribute("ip", "IPv4 Address",
44 mac = Attribute("mac", "MAC Address",
47 prefix = Attribute("prefix", "IPv4 network prefix",
50 mtu = Attribute("mtu", "Maximum transmition unit for device",
53 devname = Attribute("deviceName",
54 "Name of the network interface (e.g. eth0, wlan0, etc)",
55 flags = Flags.NoWrite)
57 up = Attribute("up", "Link up", default=True,
60 pointopoint = Attribute("pointopoint", "Peer IP address",
63 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
66 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
69 gre_key = Attribute("greKey",
70 "GRE key to be used to configure GRE tunnel",
74 gre_remote = Attribute("greRemote",
75 "Public IP of remote endpoint for GRE tunnel",
78 pi = Attribute("pi", "Add PI (protocol information) header",
82 tear_down = Attribute("tearDown",
83 "Bash script to be executed before releasing the resource",
86 cls._register_attribute(ip)
87 cls._register_attribute(mac)
88 cls._register_attribute(prefix)
89 cls._register_attribute(mtu)
90 cls._register_attribute(devname)
91 cls._register_attribute(up)
92 cls._register_attribute(pointopoint)
93 cls._register_attribute(txqueuelen)
94 cls._register_attribute(gre_key)
95 cls._register_attribute(gre_remote)
96 cls._register_attribute(pi)
97 cls._register_attribute(tear_down)
99 def __init__(self, ec, guid):
100 super(LinuxTap, self).__init__(ec, guid)
101 self._gre_enabled = None
102 self._vif_prefix = "tap"
103 self._vif_type = "IFF_TAP"
104 self._vif_type_flag = LinuxTap.IFF_TAP
105 self._home = "%s-%s" % (self.vif_prefix, self.guid)
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 self._gre_enabled is None:
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
122 def upload_sources(self):
125 # udp-connect python script
126 udp_connect = os.path.join(os.path.dirname(__file__), "scripts",
127 "linux-udp-connect.py")
129 scripts.append(udp_connect)
131 tap_create = os.path.join(os.path.dirname(__file__), "scripts",
132 "linux-tap-create.py")
134 scripts.append(tap_create)
136 tap_delete = os.path.join(os.path.dirname(__file__), "scripts",
137 "linux-tap-delete.py")
139 scripts.append(tap_delete)
141 # tunnel creation python script
142 tunchannel = os.path.join(os.path.dirname(__file__), "scripts",
145 scripts.append(tunchannel)
148 scripts = ";".join(scripts)
150 self.node.upload(scripts,
151 os.path.join(self.node.src_dir),
154 # upload stop.sh script
155 stop_command = self.replace_paths(self._stop_command)
157 self.node.upload(stop_command,
158 os.path.join(self.app_home, "stop.sh"),
160 # Overwrite file every time.
161 # The stop.sh has the path to the socket, which should change
162 # on every experiment run.
165 def upload_start_command(self):
166 # If GRE mode is enabled, TAP creation is delayed until the
167 # tunnel is established
168 if not self.gre_enabled:
169 # We want to make sure the device is up and running
170 # before the deploy is over, so we execute the
171 # start script now and wait until it finishes.
172 command = self.get("command")
173 command = self.replace_paths(command)
175 shfile = os.path.join(self.app_home, "start.sh")
176 self.node.run_and_wait(command, self.run_home,
180 def upload_start_command(self):
181 # If GRE mode is enabled, TAP creation is delayed until the
182 # tunnel is established
183 if not self.gre_enabled:
184 # Overwrite file every time.
185 # The start.sh has the path to the socket, wich should change
186 # on every experiment run.
187 command = self.get("command")
189 self.info("Uploading command '%s'" % command)
191 # replace application specific paths in the command
192 command = self.replace_paths(command)
194 # replace application specific paths in the environment
195 env = self.get("env")
196 env = env and self.replace_paths(env)
198 shfile = os.path.join(self.app_home, "start.sh")
200 self.node.upload_command(command,
205 # We want to make sure the device is up and running
206 # before the deploy finishes, so we execute now the
207 # start script. We run it in background, because the
208 # TAP will live for as long as the process that
209 # created it is running, and wait until the TAP
211 self._run_in_background()
214 if not self.node or self.node.state < ResourceState.PROVISIONED:
215 self.ec.schedule(self.reschedule_delay, self.deploy)
218 self._vif_prefix = "gre"
219 self._home = "%s-%s" % (self.vif_prefix, self.guid)
221 if not self.get("deviceName"):
222 self.set("deviceName", "%s%d" % (self.vif_prefix, self.guid))
224 if not self.get("command"):
225 self.set("command", self._start_command)
227 if not self.get("depends"):
228 self.set("depends", self._dependencies)
230 if not self.get("install"):
231 self.set("install", self._install)
239 if self.state == ResourceState.READY:
240 command = self.get("command")
241 self.info("Starting command '%s'" % command)
245 msg = " Failed to execute command '%s'" % command
246 self.error(msg, out, err)
247 raise RuntimeError, msg
250 command = self.get('command') or ''
252 if self.state == ResourceState.STARTED:
253 self.info("Stopping command '%s'" % command)
255 command = "bash %s" % os.path.join(self.app_home, "stop.sh")
256 (out, err), proc = self.execute_command(command,
260 msg = " Failed to stop command '%s' " % command
261 self.error(msg, out, err)
267 state_check_delay = 0.5
268 if self._state == ResourceState.STARTED and \
269 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
271 if self.get("deviceName"):
272 (out, err), proc = self.node.execute("ifconfig")
274 if out.strip().find(self.get("deviceName")) == -1:
275 # tap is not running is not running (socket not found)
278 self._last_state_check = tnow()
282 def do_release(self):
283 # Node needs to wait until all associated RMs are released
285 from nepi.resources.linux.tunnel import LinuxTunnel
286 rms = self.get_connected(LinuxTunnel.get_rtype())
289 if rm.state < ResourceState.STOPPED:
290 self.ec.schedule(self.reschedule_delay, self.release)
293 super(LinuxTap, self).do_release()
295 def gre_connect(self, remote_endpoint, connection_app_home,
296 connection_run_home):
297 gre_connect_command = self._gre_connect_command(remote_endpoint,
298 connection_app_home, connection_run_home)
300 # upload command to connect.sh script
301 shfile = os.path.join(connection_app_home, "gre-connect.sh")
302 self.node.upload_command(gre_connect_command,
306 # invoke connect script
307 cmd = "bash %s" % shfile
308 (out, err), proc = self.node.run(cmd, connection_run_home,
309 pidfile = "gre_connect_pidfile",
310 stdout = "gre_connect_stdout",
311 stderr = "gre_connect_stderr",
314 # check if execution errors occurred
315 msg = " Failed to connect endpoints "
317 if proc.poll() or err:
318 self.error(msg, out, err)
319 raise RuntimeError, msg
321 # Wait for pid file to be generated
322 pid, ppid = self.node.wait_pid(connection_run_home,
323 pidfile = "gre_connect_pidfile")
325 # If the process is not running, check for error information
326 # on the remote machine
327 if not pid or not ppid:
328 (out, err), proc = self.node.check_errors(connection_run_home,
329 stderr = "gre_connect_stderr")
331 # Out is what was written in the stderr file
333 msg = " Failed to start command '%s' " % command
334 self.error(msg, out, err)
335 raise RuntimeError, msg
339 def initiate_udp_connection(self, remote_endpoint, connection_app_home,
340 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
341 port = self.udp_connect(remote_endpoint, connection_app_home,
342 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
345 def udp_connect(self, remote_endpoint, connection_app_home,
346 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
347 udp_connect_command = self._udp_connect_command(
348 remote_endpoint, connection_app_home, connection_run_home,
349 cipher, cipher_key, bwlimit, txqueuelen)
351 # upload command to connect.sh script
352 shfile = os.path.join(connection_app_home, "udp-connect.sh")
353 self.node.upload_command(udp_connect_command,
357 # invoke connect script
358 cmd = "bash %s" % shfile
359 (out, err), proc = self.node.run(cmd, connection_run_home,
360 pidfile = "udp_connect_pidfile",
361 stdout = "udp_connect_stdout",
362 stderr = "udp_connect_stderr",
365 # check if execution errors occurred
366 msg = "Failed to connect endpoints "
369 self.error(msg, out, err)
370 raise RuntimeError, msg
372 # Wait for pid file to be generated
373 self._pid, self._ppid = self.node.wait_pid(
375 pidfile = "udp_connect_pidfile")
377 # If the process is not running, check for error information
378 # on the remote machine
379 if not self._pid or not self._ppid:
380 (out, err), proc = self.node.check_errors(
382 stderr = "udp_connect_stderr")
384 # Out is what was written in the stderr file
386 msg = " Failed to start command '%s' " % command
387 self.error(msg, out, err)
388 raise RuntimeError, msg
390 return self.wait_file(connection_run_home, "local_port")
392 def establish_udp_connection(self, remote_endpoint,
393 connection_app_home, connection_run_home, port):
394 # upload remote port number to file
395 rem_port = "%s\n" % port
396 self.node.upload(rem_port,
397 os.path.join(connection_run_home, "remote_port"),
401 def verify_connection(self, remote_endpoint,
402 connection_app_home, connection_run_home):
404 return self.wait_file(connection_run_home, "ret_file")
406 def terminate_connection(self, remote_endpoint,
407 connection_app_home, connection_run_home):
408 if self._pid and self._ppid:
409 (out, err), proc = self.node.kill(self._pid, self._ppid,
412 # check if execution errors occurred
413 if proc.poll() and err:
414 msg = " Failed to Kill the Tap"
415 self.error(msg, out, err)
416 raise RuntimeError, msg
418 def check_status(self):
419 return self.node.status(self._pid, self._ppid)
421 def wait_file(self, home, filename):
422 """ Waits until file on endpoint is generated """
427 (out, err), proc = self.node.check_output(home, filename)
435 msg = "Couldn't retrieve %s" % filename
436 self.error(msg, out, err)
437 raise RuntimeError, msg
442 def _start_command(self):
446 command = ["sudo -S "]
447 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
448 command.append("python ${SRC}/linux-tap-create.py")
449 command.append("-t %s" % self.vif_type)
450 command.append("-a %s" % self.get("ip"))
451 command.append("-n %s" % self.get("prefix"))
452 command.append("-N %s " % self.get("deviceName"))
453 command.append("-S %s " % self.sock_name)
457 return " ".join(command)
460 def _stop_command(self):
462 command = self._stop_gre_command
464 command = ["sudo -S "]
465 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
466 command.append("python ${SRC}/linux-tap-delete.py")
467 command.append("-N %s " % self.get("deviceName"))
468 command.append("-S %s " % self.sock_name)
469 command = " ".join(command)
473 def _gre_connect_command(self, remote_endpoint,
474 connection_app_home, connecrion_app_home):
475 # Set the remote endpoint to (private) device IP
476 self.set("pointopoint", remote_endpoint.get("ip"))
478 self.set("greRemote", remote_endpoint.node.get("ip"))
480 # Generate GRE connect command
482 command.append(self._stop_gre_command)
483 command.append(") ; (")
484 command.append(self._start_gre_command)
487 command = " ".join(command)
488 command = self.replace_paths(command)
493 def _start_gre_command(self):
495 command.append("sudo -S modprobe ip_gre")
496 command.append("sudo -S ip tunnel add %s mode gre remote %s local %s ttl 255 csum key %s" % (
497 self.get("deviceName"),
498 self.get("greRemote"),
502 command.append("sudo -S ip addr add %s/%s peer %s/%s dev %s" % (
505 self.get("pointopoint"),
507 self.get("deviceName"),
509 command.append("sudo -S ip link set %s up " % self.get("deviceName"))
511 return ";".join(command)
514 def _stop_gre_command(self):
516 command.append("sudo -S modprobe -r ip_gre")
517 command.append("sudo -S ip link set down dev %s" % (
518 self.get("deviceName"),
520 command.append("sudo -S ip link del dev %s" % (
521 self.get("deviceName"),
524 return ";".join(command)
526 def _udp_connect_command(self, remote_endpoint,
527 connection_app_home, connection_run_home,
528 cipher, cipher_key, bwlimit, txqueuelen):
530 # Set the remote endpoint to the IP of the device
531 self.set("pointopoint", remote_endpoint.get("ip"))
533 # Public IP of the remote NODE to stablish tunnel
534 remote_ip = remote_endpoint.node.get("ip")
535 local_ip = self.node.get("ip")
537 local_port_file = os.path.join(connection_run_home,
540 remote_port_file = os.path.join(connection_run_home,
543 ret_file = os.path.join(connection_run_home,
546 # Generate UDP connect command
547 # Use the start command to configure TAP with peer info
548 start_command = self._start_command
551 # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
552 command.append("sudo -S")
553 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
554 command.append("python ${SRC}/linux-udp-connect.py")
555 command.append("-t %s" % self.vif_type)
556 command.append("-S %s " % self.sock_name)
557 command.append("-p %s " % local_port_file)
558 command.append("-P %s " % remote_port_file)
559 command.append("-o %s " % local_ip)
560 command.append("-O %s " % remote_ip)
561 command.append("-R %s " % ret_file)
565 command.append("-c %s " % cipher)
567 command.append("-k %s " % cipher_key)
569 command.append("-q %s " % txqueuelen)
571 command.append("-b %s " % bwlimit)
573 command = " ".join(command)
574 command = self.replace_paths(command)
579 def _dependencies(self):
580 return "mercurial make gcc"
584 # Install python-vsys and python-passfd
585 install_passfd = ( " ( python -c 'import passfd' ) "
589 " hg clone http://nepi.inria.fr/code/python-passfd ; "
590 " cd python-passfd ; "
592 " sudo -S make install "
595 return install_passfd
597 def valid_connection(self, guid):
603 return self._vif_type
606 def vif_type_flag(self):
607 return self._vif_type_flag
610 def vif_prefix(self):
611 return self._vif_prefix
615 return os.path.join(self.run_home, "%s.sock" % self.vif_prefix)
617 def valid_connection(self, guid):