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