Changed the endpoint_ip and endpoint_prefix attributes of TAP/TUN endpoints for ip...
[nepi.git] / src / nepi / resources / linux / tap.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
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.
9 #
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.
14 #
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/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
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
25
26 import os
27 import time
28
29 PYTHON_VSYS_VERSION = "1.0"
30
31 @clsinit_copy
32 class LinuxTap(LinuxApplication):
33     _rtype = "linux::Tap"
34     _help = "Creates a TAP device on a Linux host"
35     _backend = "linux"
36
37     IFF_TUN = 0x0001
38     IFF_TAP = 0x0002
39
40     @classmethod
41     def _register_attributes(cls):
42         ip = Attribute("ip", "IPv4 Address",
43               flags = Flags.Design)
44
45         mac = Attribute("mac", "MAC Address",
46                 flags = Flags.Design)
47
48         prefix = Attribute("prefix", "IPv4 network prefix",
49                 flags = Flags.Design)
50
51         mtu = Attribute("mtu", "Maximum transmition unit for device",
52                 type = Types.Integer)
53
54         devname = Attribute("deviceName", 
55                 "Name of the network interface (e.g. eth0, wlan0, etc)",
56                 flags = Flags.NoWrite)
57
58         up = Attribute("up", "Link up", 
59                 type = Types.Bool)
60         
61         pointopoint = Attribute("pointopoint", "Peer IP address", 
62                 flags = Flags.Design)
63
64         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
65                 flags = Flags.Design)
66
67         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
68                 flags = Flags.Design)
69
70         gre_key = Attribute("greKey", 
71                 "GRE key to be used to configure GRE tunnel", 
72                 default = "1",
73                 flags = Flags.Design)
74
75         gre_remote = Attribute("greRemote", 
76                 "Public IP of remote endpoint for GRE tunnel", 
77                 flags = Flags.Design)
78
79         pi = Attribute("pi", "Add PI (protocol information) header", 
80                 default = False,
81                 type = Types.Bool)
82  
83         tear_down = Attribute("tearDown", 
84                 "Bash script to be executed before releasing the resource",
85                 flags = Flags.Design)
86
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)
99
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
105
106     @property
107     def node(self):
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"
111
112     @property
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
118
119         return self._gre_enabled
120
121     @property
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
127
128         return self._tunnel_mode
129
130     def upload_sources(self):
131         scripts = []
132
133         # udp-connect python script
134         udp_connect = os.path.join(os.path.dirname(__file__), "scripts",
135                 "linux-udp-connect.py")
136         
137         scripts.append(udp_connect)
138
139         # tunnel creation python script
140         tunchannel = os.path.join(os.path.dirname(__file__), "scripts", 
141                 "tunchannel.py")
142
143         scripts.append(tunchannel)
144
145         # Upload scripts
146         scripts = ";".join(scripts)
147
148         self.node.upload(scripts,
149                 os.path.join(self.node.src_dir),
150                 overwrite = False)
151
152         # upload stop.sh script
153         stop_command = self.replace_paths(self._stop_command)
154
155         self.node.upload(stop_command,
156                 os.path.join(self.app_home, "stop.sh"),
157                 text = True,
158                 # Overwrite file every time. 
159                 # The stop.sh has the path to the socket, which should change
160                 # on every experiment run.
161                 overwrite = True)
162
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)
172
173             shfile = os.path.join(self.app_home, "start.sh")
174             self.node.run_and_wait(command, self.run_home,
175                 shfile = shfile,
176                 overwrite = True)
177
178     def do_deploy(self):
179         if not self.node or self.node.state < ResourceState.PROVISIONED:
180             self.ec.schedule(self.reschedule_delay, self.deploy)
181         else:
182             if not self.get("deviceName"):
183                 self.set("deviceName", "%s%d" % (self.vif_prefix, self.guid)) 
184
185             if not self.get("command"):
186                 self.set("command", self._start_command)
187
188             self.do_discover()
189             self.do_provision()
190
191             self.set_ready()
192
193     def do_start(self):
194         if self.state == ResourceState.READY:
195             command = self.get("command")
196             self.info("Starting command '%s'" % command)
197
198             self.set_started()
199         else:
200             msg = " Failed to execute command '%s'" % command
201             self.error(msg, out, err)
202             raise RuntimeError, msg
203
204     def do_stop(self):
205         command = self.get('command') or ''
206         
207         if self.state == ResourceState.STARTED:
208             self.info("Stopping command '%s'" % command)
209
210             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
211             (out, err), proc = self.execute_command(command,
212                     blocking = True)
213
214             if err:
215                 msg = " Failed to stop command '%s' " % command
216                 self.error(msg, out, err)
217
218             self.set_stopped()
219
220     @property
221     def state(self):
222         state_check_delay = 0.5
223         if self._state == ResourceState.STARTED and \
224                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
225
226             if self.get("deviceName"):
227                 (out, err), proc = self.node.execute("ip a")
228
229                 if out.strip().find(self.get("deviceName")) == -1: 
230                     # tap is not running is not running (socket not found)
231                     self.set_stopped()
232
233             self._last_state_check = tnow()
234
235         return self._state
236
237     def do_release(self):
238         # Node needs to wait until all associated RMs are released
239         # to be released
240         from nepi.resources.linux.tunnel import LinuxTunnel
241         rms = self.get_connected(LinuxTunnel.get_rtype())
242
243         for rm in rms:
244             if rm.state < ResourceState.STOPPED:
245                 self.ec.schedule(self.reschedule_delay, self.release)
246                 return 
247
248         super(LinuxTap, self).do_release()
249
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)
254
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,
258                 shfile = shfile,
259                 overwrite = False)
260
261         # invoke connect script
262         cmd = "bash %s" % shfile
263         (out, err), proc = self.node.run(cmd, connection_run_home)
264              
265         # check if execution errors occurred
266         msg = " Failed to connect endpoints "
267         
268         if proc.poll() or err:
269             self.error(msg, out, err)
270             raise RuntimeError, msg
271     
272         # Wait for pid file to be generated
273         pid, ppid = self.node.wait_pid(connection_run_home)
274         
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
280             if err:
281                 msg = " Failed to start command '%s' " % command
282                 self.error(msg, out, err)
283                 raise RuntimeError, msg
284         
285         return True
286
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)
291         return port
292
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)
298
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,
302                 shfile = shfile,
303                 overwrite = False)
304
305         # invoke connect script
306         cmd = "bash %s" % shfile
307         (out, err), proc = self.node.run(cmd, self.run_home) 
308              
309         # check if execution errors occurred
310         msg = "Failed to connect endpoints "
311         
312         if proc.poll():
313             self.error(msg, out, err)
314             raise RuntimeError, msg
315     
316         # Wait for pid file to be generated
317         self._pid, self._ppid = self.node.wait_pid(self.run_home)
318         
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
324             if err:
325                 msg = " Failed to start command '%s' " % command
326                 self.error(msg, out, err)
327                 raise RuntimeError, msg
328
329         port = self.wait_local_port()
330
331         return port
332
333     def _udp_connect_command(self, remote_endpoint, connection_run_home, 
334             cipher, cipher_key, bwlimit, txqueuelen):
335
336         # Set the remote endpoint to the IP of the device
337         self.set("pointopoint", remote_endpoint.get("ip"))
338         
339         # Planetlab TAPs always use PI headers
340         from nepi.resources.planetlab.tap import PlanetlabTap
341         if self.is_rm_instance(PlanetlabTap.get_rtype()):
342             self.set("pi", True)
343
344         # Public IP of the remote NODE to stablish tunnel
345         remote_ip = remote_endpoint.node.get("ip")
346
347         local_port_file = os.path.join(self.run_home, 
348                 "local_port")
349
350         remote_port_file = os.path.join(self.run_home, 
351                 "remote_port")
352
353         ret_file = os.path.join(self.run_home, 
354                 "ret_file")
355
356         # Generate UDP connect command
357         # Use the start command to configure TAP with peer info
358         start_command = self._start_command
359         
360         command = ["( "]
361         command.append(start_command)
362
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)
370         if self.get("pi"):
371             command.append("-p")
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)
376         if cipher:
377             command.append("-c %s " % cipher)
378         if cipher_key:
379             command.append("-k %s " % cipher_key)
380         if txqueuelen:
381             command.append("-q %s " % txqueuelen)
382         if bwlimit:
383             command.append("-b %s " % bwlimit)
384
385         command.append(")")
386
387         command = " ".join(command)
388         command = self.replace_paths(command)
389
390         return command
391
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"))
395         ## public node IP
396         self.set("greRemote", remote_endpoint.node.get("ip"))
397
398         # Generate GRE connect command
399         command = ["("]
400         command.append(self._stop_command)
401         command.append(") ; (")
402         command.append(self._start_gre_command)
403         command.append(")")
404
405         command = " ".join(command)
406         command = self.replace_paths(command)
407
408         return command
409
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"),
415                 text = True, 
416                 overwrite = False)
417
418     def verify_connection(self):
419         self.wait_result()
420
421     def terminate_connection(self):
422         if  self._pid and self._ppid:
423             (out, err), proc = self.node.kill(self._pid, self._ppid, 
424                     sudo = True) 
425
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
431
432     def check_status(self):
433         return self.node.status(self._pid, self._ppid)
434
435     def wait_local_port(self):
436         """ Waits until the local_port file for the endpoint is generated, 
437         and returns the port number 
438         
439         """
440         return self.wait_file("local_port")
441
442     def wait_result(self):
443         """ Waits until the return code file for the endpoint is generated 
444         
445         """ 
446         return self.wait_file("ret_file")
447  
448     def wait_file(self, filename):
449         """ Waits until file on endpoint is generated """
450         result = None
451         delay = 1.0
452
453         for i in xrange(20):
454             (out, err), proc = self.node.check_output(
455                     self.run_home, filename)
456             if out:
457                 result = out.strip()
458                 break
459             else:
460                 time.sleep(delay)
461                 delay = delay * 1.5
462         else:
463             msg = "Couldn't retrieve %s" % filename
464             self.error(msg, out, err)
465             raise RuntimeError, msg
466
467         return result
468
469     @property
470     def _start_command(self):
471         command = []
472         if not self.gre_enabled:
473             # Make sure to clean TAP if it existed
474             stop_command = self._stop_command
475             
476             start_command = []
477             start_command.append("sudo -S ip tuntap add %s mode %s %s" % (
478                 self.get("deviceName"),
479                 self.vif_prefix,
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" % (
483                 self.get("ip"),
484                 self.get("prefix"),
485                 self.get("deviceName"),
486                 ))
487
488             start_command = ";".join(start_command)
489
490             command.append("(")
491             command.append(stop_command)
492             command.append(") ; (")
493             command.append(start_command)
494             command.append(")")
495
496         return " ".join(command)
497
498     @property
499     def _stop_command(self):
500         command = []
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"))
503         
504         return ";".join(command)
505
506     @property
507     def _start_gre_command(self):
508         command = []
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"),
513                 self.node.get("ip"),
514                 self.get("greKey")
515             ))
516         command.append("sudo -S ip addr add %s/%s peer %s/%s dev %s" % (
517                 self.get("ip"),
518                 self.get("prefix"),
519                 self.get("pointopoint"),
520                 self.get("prefix"),
521                 self.get("deviceName"),
522                 ))
523         command.append("sudo -S ip link set %s up " % self.get("deviceName"))
524
525         return ";".join(command)
526
527     @property
528     def vif_type(self):
529         return "IFF_TAP"
530
531     @property
532     def vif_type_flag(self):
533         return LinuxTap.IFF_TAP
534  
535     @property
536     def vif_prefix(self):
537         return "tap"
538
539     def sock_name(self):
540         return os.path.join(self.run_home, "tap.sock")
541
542     def valid_connection(self, guid):
543         # TODO: Validate!
544         return True
545