81fbe562714196628fcdb6b344295514c476bca0
[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
36     IFF_TUN = 0x0001
37     IFF_TAP = 0x0002
38
39     @classmethod
40     def _register_attributes(cls):
41         ip = Attribute("ip", "IPv4 Address",
42               flags = Flags.Design)
43
44         mac = Attribute("mac", "MAC Address",
45                 flags = Flags.Design)
46
47         prefix = Attribute("prefix", "IPv4 network prefix",
48                 flags = Flags.Design)
49
50         mtu = Attribute("mtu", "Maximum transmition unit for device",
51                 type = Types.Integer)
52
53         devname = Attribute("deviceName", 
54                 "Name of the network interface (e.g. eth0, wlan0, etc)",
55                 flags = Flags.NoWrite)
56
57         up = Attribute("up", "Link up", default=True,
58                 type = Types.Bool)
59         
60         pointopoint = Attribute("pointopoint", "Peer IP address", 
61                 flags = Flags.Design)
62
63         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
64                 flags = Flags.Design)
65
66         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
67                 flags = Flags.Design)
68
69         gre_key = Attribute("greKey", 
70                 "GRE key to be used to configure GRE tunnel", 
71                 default = "1",
72                 flags = Flags.Design)
73
74         gre_remote = Attribute("greRemote", 
75                 "Public IP of remote endpoint for GRE tunnel", 
76                 flags = Flags.Design)
77
78         pi = Attribute("pi", "Add PI (protocol information) header", 
79                 default = False,
80                 type = Types.Bool)
81  
82         tear_down = Attribute("tearDown", 
83                 "Bash script to be executed before releasing the resource",
84                 flags = Flags.Design)
85
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)
98
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)
106  
107     @property
108     def node(self):
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"
112
113     @property
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
119
120         return self._gre_enabled
121
122     def upload_sources(self):
123         scripts = []
124
125         # udp-connect python script
126         udp_connect = os.path.join(os.path.dirname(__file__), "scripts",
127                 "linux-udp-connect.py")
128         
129         scripts.append(udp_connect)
130
131         tap_create = os.path.join(os.path.dirname(__file__), "scripts",
132                 "linux-tap-create.py")
133         
134         scripts.append(tap_create)
135
136         tap_delete = os.path.join(os.path.dirname(__file__), "scripts",
137                 "linux-tap-delete.py")
138         
139         scripts.append(tap_delete)
140
141         # tunnel creation python script
142         tunchannel = os.path.join(os.path.dirname(__file__), "scripts", 
143                 "tunchannel.py")
144
145         scripts.append(tunchannel)
146
147         # Upload scripts
148         scripts = ";".join(scripts)
149
150         self.node.upload(scripts,
151                 os.path.join(self.node.src_dir),
152                 overwrite = False)
153
154         # upload stop.sh script
155         stop_command = self.replace_paths(self._stop_command)
156
157         self.node.upload(stop_command,
158                 os.path.join(self.app_home, "stop.sh"),
159                 text = True,
160                 # Overwrite file every time. 
161                 # The stop.sh has the path to the socket, which should change
162                 # on every experiment run.
163                 overwrite = True)
164
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)
174
175             shfile = os.path.join(self.app_home, "start.sh")
176             self.node.run_and_wait(command, self.run_home,
177                 shfile = shfile,
178                 overwrite = True)
179
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")
188             
189             self.info("Uploading command '%s'" % command)
190             
191             # replace application specific paths in the command
192             command = self.replace_paths(command)
193             
194             # replace application specific paths in the environment
195             env = self.get("env")
196             env = env and self.replace_paths(env)
197
198             shfile = os.path.join(self.app_home, "start.sh")
199
200             self.node.upload_command(command, 
201                     shfile = shfile,
202                     env = env,
203                     overwrite = True)
204
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  
210             # is created. 
211             self._run_in_background()
212             
213     def do_deploy(self):
214         if not self.node or self.node.state < ResourceState.PROVISIONED:
215             self.ec.schedule(self.reschedule_delay, self.deploy)
216         else:
217             if self.gre_enabled:
218                 self._vif_prefix = "gre"
219                 self._home = "%s-%s" % (self.vif_prefix, self.guid)
220
221             if not self.get("deviceName"):
222                 self.set("deviceName", "%s%d" % (self.vif_prefix, self.guid)) 
223
224             if not self.get("command"):
225                 self.set("command", self._start_command)
226
227             if not self.get("depends"):
228                 self.set("depends", self._dependencies)
229
230             if not self.get("install"):
231                 self.set("install", self._install)
232
233             self.do_discover()
234             self.do_provision()
235
236             self.set_ready()
237
238     def do_start(self):
239         if self.state == ResourceState.READY:
240             command = self.get("command")
241             self.info("Starting command '%s'" % command)
242
243             self.set_started()
244         else:
245             msg = " Failed to execute command '%s'" % command
246             self.error(msg, out, err)
247             raise RuntimeError, msg
248
249     def do_stop(self):
250         command = self.get('command') or ''
251         
252         if self.state == ResourceState.STARTED:
253             self.info("Stopping command '%s'" % command)
254
255             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
256             (out, err), proc = self.execute_command(command,
257                     blocking = True)
258
259             if err:
260                 msg = " Failed to stop command '%s' " % command
261                 self.error(msg, out, err)
262
263             self.set_stopped()
264
265     @property
266     def state(self):
267         state_check_delay = 0.5
268         if self._state == ResourceState.STARTED and \
269                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
270
271             if self.get("deviceName"):
272                 (out, err), proc = self.node.execute("ifconfig")
273
274                 if out.strip().find(self.get("deviceName")) == -1: 
275                     # tap is not running is not running (socket not found)
276                     self.set_stopped()
277
278             self._last_state_check = tnow()
279
280         return self._state
281
282     def do_release(self):
283         # Node needs to wait until all associated RMs are released
284         # to be released
285         from nepi.resources.linux.tunnel import LinuxTunnel
286         rms = self.get_connected(LinuxTunnel.get_rtype())
287
288         for rm in rms:
289             if rm.state < ResourceState.STOPPED:
290                 self.ec.schedule(self.reschedule_delay, self.release)
291                 return 
292
293         super(LinuxTap, self).do_release()
294
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)
299
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,
303                 shfile = shfile,
304                 overwrite = False)
305
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", 
312                 )
313              
314         # check if execution errors occurred
315         msg = " Failed to connect endpoints "
316         
317         if proc.poll() or err:
318             self.error(msg, out, err)
319             raise RuntimeError, msg
320     
321         # Wait for pid file to be generated
322         pid, ppid = self.node.wait_pid(connection_run_home, 
323                 pidfile = "gre_connect_pidfile")
324         
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") 
330
331             # Out is what was written in the stderr file
332             if err:
333                 msg = " Failed to start command '%s' " % command
334                 self.error(msg, out, err)
335                 raise RuntimeError, msg
336         
337         return True
338
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)
343         return port
344
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)
350
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,
354                 shfile = shfile,
355                 overwrite = False)
356
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", 
363                 ) 
364              
365         # check if execution errors occurred
366         msg = "Failed to connect endpoints "
367         
368         if proc.poll():
369             self.error(msg, out, err)
370             raise RuntimeError, msg
371     
372         # Wait for pid file to be generated
373         self._pid, self._ppid = self.node.wait_pid(
374                 connection_run_home,
375                 pidfile = "udp_connect_pidfile")
376         
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(
381                     connection_run_home,
382                     stderr = "udp_connect_stderr")
383
384             # Out is what was written in the stderr file
385             if err:
386                 msg = " Failed to start command '%s' " % command
387                 self.error(msg, out, err)
388                 raise RuntimeError, msg
389
390         return self.wait_file(connection_run_home, "local_port")
391
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"),
398                 text = True, 
399                 overwrite = False)
400
401     def verify_connection(self, remote_endpoint,
402             connection_app_home, connection_run_home):
403
404         return self.wait_file(connection_run_home, "ret_file")
405
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, 
410                     sudo = True) 
411
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
417
418     def check_status(self):
419         return self.node.status(self._pid, self._ppid)
420
421     def wait_file(self, home, filename):
422         """ Waits until file on endpoint is generated """
423         result = None
424         delay = 1.0
425
426         for i in xrange(20):
427             (out, err), proc = self.node.check_output(home, filename)
428             if out:
429                 result = out.strip()
430                 break
431             else:
432                 time.sleep(delay)
433                 delay = delay * 1.5
434         else:
435             msg = "Couldn't retrieve %s" % filename
436             self.error(msg, out, err)
437             raise RuntimeError, msg
438
439         return result
440
441     @property
442     def _start_command(self):
443         if self.gre_enabled:
444             command = []
445         else:
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)
454             if self.get("pi"):
455                 command.append("-p")
456
457         return " ".join(command)
458
459     @property
460     def _stop_command(self):
461         if self.gre_enabled:
462             command = self._stop_gre_command
463         else:
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)
470
471         return command
472
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"))
477         ## public node IP
478         self.set("greRemote", remote_endpoint.node.get("ip"))
479
480         # Generate GRE connect command
481         command = ["("]
482         command.append(self._stop_gre_command)
483         command.append(") ; (")
484         command.append(self._start_gre_command)
485         command.append(")")
486
487         command = " ".join(command)
488         command = self.replace_paths(command)
489
490         return command
491
492     @property
493     def _start_gre_command(self):
494         command = []
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"),
499                 self.node.get("ip"),
500                 self.get("greKey")
501             ))
502         command.append("sudo -S ip addr add %s/%s peer %s/%s dev %s" % (
503                 self.get("ip"),
504                 self.get("prefix"),
505                 self.get("pointopoint"),
506                 self.get("prefix"),
507                 self.get("deviceName"),
508                 ))
509         command.append("sudo -S ip link set %s up " % self.get("deviceName"))
510
511         return ";".join(command)
512
513     @property
514     def _stop_gre_command(self):
515         command = []
516         command.append("sudo -S modprobe -r ip_gre")
517         command.append("sudo -S ip link set down dev %s" % (
518                 self.get("deviceName"),
519             ))
520         command.append("sudo -S ip link del dev %s" % (
521                 self.get("deviceName"),
522                 ))
523
524         return ";".join(command)
525
526     def _udp_connect_command(self, remote_endpoint, 
527             connection_app_home, connection_run_home,
528             cipher, cipher_key, bwlimit, txqueuelen):
529
530         # Set the remote endpoint to the IP of the device
531         self.set("pointopoint", remote_endpoint.get("ip"))
532         
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")
536
537         local_port_file = os.path.join(connection_run_home, 
538                 "local_port")
539
540         remote_port_file = os.path.join(connection_run_home, 
541                 "remote_port")
542
543         ret_file = os.path.join(connection_run_home, 
544                 "ret_file")
545
546         # Generate UDP connect command
547         # Use the start command to configure TAP with peer info
548         start_command = self._start_command
549         
550         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)
562         if self.get("pi"):
563             command.append("-n")
564         if cipher:
565             command.append("-c %s " % cipher)
566         if cipher_key:
567             command.append("-k %s " % cipher_key)
568         if txqueuelen:
569             command.append("-q %s " % txqueuelen)
570         if bwlimit:
571             command.append("-b %s " % bwlimit)
572
573         command = " ".join(command)
574         command = self.replace_paths(command)
575
576         return command
577     
578     @property
579     def _dependencies(self):
580         return "mercurial make gcc"
581
582     @property
583     def _install(self):
584         # Install python-vsys and python-passfd
585         install_passfd = ( " ( python -c 'import passfd' ) "
586                     " || "
587                     " ( "
588                     "   cd ${SRC} ; "
589                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
590                     "   cd python-passfd ; "
591                     "   make all ; "
592                     "   sudo -S make install "
593                     " )" )
594
595         return install_passfd
596
597     def valid_connection(self, guid):
598         # TODO: Validate!
599         return True
600
601     @property
602     def vif_type(self):
603         return self._vif_type
604
605     @property
606     def vif_type_flag(self):
607         return self._vif_type_flag
608  
609     @property
610     def vif_prefix(self):
611         return self._vif_prefix
612
613     @property
614     def sock_name(self):
615         return os.path.join(self.run_home, "%s.sock" % self.vif_prefix)
616
617     def valid_connection(self, guid):
618         # TODO: Validate!
619         return True
620