Fixing UdpTunnel unit tests for PlanetLab
[nepi.git] / src / nepi / resources / planetlab / 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         reschedule_delay
23 from nepi.resources.linux.application import LinuxApplication
24 from nepi.resources.planetlab.node import PlanetlabNode
25 from nepi.util.timefuncs import tnow, tdiffsec
26
27 import os
28 import time
29
30 # TODO:
31 #       - CREATE GRE - PlanetlabGRE - it only needs to set the gre and remote
32 #               properties when configuring the vif_up
33
34 PYTHON_VSYS_VERSION = "1.0"
35
36 @clsinit_copy
37 class PlanetlabTap(LinuxApplication):
38     _rtype = "PlanetlabTap"
39     _help = "Creates a TAP device on a PlanetLab host"
40     _backend = "planetlab"
41
42     @classmethod
43     def _register_attributes(cls):
44         ip4 = Attribute("ip4", "IPv4 Address",
45               flags = Flags.Design)
46
47         mac = Attribute("mac", "MAC Address",
48                 flags = Flags.Design)
49
50         prefix4 = Attribute("prefix4", "IPv4 network prefix",
51                 type = Types.Integer,
52                 flags = Flags.Design)
53
54         mtu = Attribute("mtu", "Maximum transmition unit for device",
55                 type = Types.Integer)
56
57         devname = Attribute("deviceName", 
58                 "Name of the network interface (e.g. eth0, wlan0, etc)",
59                 flags = Flags.NoWrite)
60
61         up = Attribute("up", "Link up", 
62                 type = Types.Bool)
63         
64         snat = Attribute("snat", "Set SNAT=1", 
65                 type = Types.Bool,
66                 flags = Flags.Design)
67         
68         pointopoint = Attribute("pointopoint", "Peer IP address", 
69                 flags = Flags.Design)
70
71         tear_down = Attribute("tearDown", "Bash script to be executed before " + \
72                 "releasing the resource",
73                 flags = Flags.Design)
74
75         cls._register_attribute(ip4)
76         cls._register_attribute(mac)
77         cls._register_attribute(prefix4)
78         cls._register_attribute(mtu)
79         cls._register_attribute(devname)
80         cls._register_attribute(up)
81         cls._register_attribute(snat)
82         cls._register_attribute(pointopoint)
83         cls._register_attribute(tear_down)
84
85     def __init__(self, ec, guid):
86         super(PlanetlabTap, self).__init__(ec, guid)
87         self._home = "tap-%s" % self.guid
88
89     @property
90     def node(self):
91         node = self.get_connected(PlanetlabNode.get_rtype())
92         if node: return node[0]
93         return None
94
95     def upload_sources(self):
96         # upload vif-creation python script
97         pl_vif_create = os.path.join(os.path.dirname(__file__), "scripts",
98                 "pl-vif-create.py")
99
100         self.node.upload(pl_vif_create,
101                 os.path.join(self.node.src_dir, "pl-vif-create.py"),
102                 overwrite = False)
103
104         # upload vif-stop python script
105         pl_vif_stop = os.path.join(os.path.dirname(__file__), "scripts",
106                 "pl-vif-stop.py")
107
108         self.node.upload(pl_vif_stop,
109                 os.path.join(self.node.src_dir, "pl-vif-stop.py"),
110                 overwrite = False)
111
112         # upload vif-connect python script
113         pl_vif_connect = os.path.join(os.path.dirname(__file__), "scripts",
114                 "pl-vif-udp-connect.py")
115
116         self.node.upload(pl_vif_connect,
117                 os.path.join(self.node.src_dir, "pl-vif-udp-connect.py"),
118                 overwrite = False)
119
120         # upload tun-connect python script
121         tunchannel = os.path.join(os.path.dirname(__file__), "..", "linux",
122                 "scripts", "tunchannel.py")
123
124         self.node.upload(tunchannel,
125                 os.path.join(self.node.src_dir, "tunchannel.py"),
126                 overwrite = False)
127
128         # upload stop.sh script
129         stop_command = self.replace_paths(self._stop_command)
130         self.node.upload(stop_command,
131                 os.path.join(self.app_home, "stop.sh"),
132                 text = True,
133                 # Overwrite file every time. 
134                 # The stop.sh has the path to the socket, wich should change
135                 # on every experiment run.
136                 overwrite = True)
137
138     def upload_start_command(self):
139         # Overwrite file every time. 
140         # The start.sh has the path to the socket, wich should change
141         # on every experiment run.
142         super(PlanetlabTap, self).upload_start_command(overwrite = True)
143
144         # We want to make sure the device is up and running
145         # before the deploy finishes, so we execute now the 
146         # start script. We run it in background, because the 
147         # TAP will live for as long as the process that 
148         # created it is running, and wait until the TAP  
149         # is created. 
150         self._run_in_background()
151         
152         # After creating the TAP, the pl-vif-create.py script
153         # will write the name of the TAP to a file. We wait until
154         # we can read the interface name from the file.
155         if_name = self.wait_if_name()
156         self.set("deviceName", if_name) 
157
158     def do_deploy(self):
159         if not self.node or self.node.state < ResourceState.PROVISIONED:
160             self.ec.schedule(reschedule_delay, self.deploy)
161         else:
162             if not self.get("command"):
163                 self.set("command", self._start_command)
164
165             if not self.get("depends"):
166                 self.set("depends", self._dependencies)
167
168             if not self.get("install"):
169                 self.set("install", self._install)
170
171             self.do_discover()
172             self.do_provision()
173
174             self.set_ready()
175
176     def do_start(self):
177         if self.state == ResourceState.READY:
178             command = self.get("command")
179             self.info("Starting command '%s'" % command)
180
181             self.set_started()
182         else:
183             msg = " Failed to execute command '%s'" % command
184             self.error(msg, out, err)
185             raise RuntimeError, msg
186
187     def do_stop(self):
188         command = self.get('command') or ''
189         
190         if self.state == ResourceState.STARTED:
191             self.info("Stopping command '%s'" % command)
192
193             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
194             (out, err), proc = self.execute_command(command,
195                     blocking = True)
196
197             self.set_stopped()
198
199     @property
200     def state(self):
201         # First check if the ccnd has failed
202         state_check_delay = 0.5
203         if self._state == ResourceState.STARTED and \
204                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
205
206             if self.get("deviceName"):
207                 (out, err), proc = self.node.execute("ifconfig")
208
209                 if out.strip().find(self.get("deviceName")) == -1: 
210                     # tap is not running is not running (socket not found)
211                     self.set_stopped()
212
213             self._last_state_check = tnow()
214
215         return self._state
216
217     def do_release(self):
218         # Node needs to wait until all associated RMs are released
219         # to be released
220         from nepi.resources.linux.udptunnel import UdpTunnel
221         rms = self.get_connected(UdpTunnel.get_rtype())
222         for rm in rms:
223             if rm.state < ResourceState.STOPPED:
224                 self.ec.schedule(reschedule_delay, self.release)
225                 return 
226
227         super(PlanetlabTap, self).do_release()
228
229     def wait_if_name(self):
230         """ Waits until the if_name file for the command is generated, 
231             and returns the if_name for the device """
232         if_name = None
233         delay = 0.5
234
235         for i in xrange(20):
236             (out, err), proc = self.node.check_output(self.run_home, "if_name")
237
238             if proc.poll() > 0:
239                 (out, err), proc = self.node.check_errors(self.run_home)
240                 
241                 if err.strip():
242                     raise RuntimeError, err
243
244             if out:
245                 if_name = out.strip()
246                 break
247             else:
248                 time.sleep(delay)
249                 delay = delay * 1.5
250         else:
251             msg = "Couldn't retrieve if_name"
252             self.error(msg, out, err)
253             raise RuntimeError, msg
254
255         return if_name
256
257     def udp_connect_command(self, remote_ip, local_port_file, 
258             remote_port_file, ret_file, cipher, cipher_key,
259             bwlimit, txqueuelen):
260         command = ["sudo -S "]
261         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
262         command.append("python ${SRC}/pl-vif-udp-connect.py")
263         command.append("-t %s" % self.vif_type)
264         command.append("-S %s " % self.sock_name)
265         command.append("-l %s " % local_port_file)
266         command.append("-r %s " % remote_port_file)
267         command.append("-H %s " % remote_ip)
268         command.append("-R %s " % ret_file)
269         if cipher:
270             command.append("-c %s " % cipher)
271         if cipher_key:
272             command.append("-k %s " % cipher_key)
273         if txqueuelen:
274             command.append("-q %s " % txqueuelen)
275         if bwlimit:
276             command.append("-b %s " % bwlimit)
277
278         command = " ".join(command)
279         command = self.replace_paths(command)
280         return command
281
282     @property
283     def _start_command(self):
284         command = ["sudo -S python ${SRC}/pl-vif-create.py"]
285         
286         command.append("-t %s" % self.vif_type)
287         command.append("-a %s" % self.get("ip4"))
288         command.append("-n %d" % self.get("prefix4"))
289         command.append("-f %s " % self.if_name_file)
290         command.append("-S %s " % self.sock_name)
291         if self.get("snat") == True:
292             command.append("-s")
293         if self.get("pointopoint"):
294             command.append("-p %s" % self.get("pointopoint"))
295
296         return " ".join(command)
297
298     @property
299     def _stop_command(self):
300         command = ["sudo -S python ${SRC}/pl-vif-stop.py"]
301         
302         command.append("-S %s " % self.sock_name)
303         return " ".join(command)
304
305     @property
306     def vif_type(self):
307         return "IFF_TAP"
308
309     @property
310     def if_name_file(self):
311         return os.path.join(self.run_home, "if_name")
312
313     @property
314     def sock_name(self):
315         return os.path.join(self.run_home, "tap.sock")
316
317     @property
318     def _dependencies(self):
319         return "mercurial make gcc"
320
321     @property
322     def _install(self):
323         # Install python-vsys and python-passfd
324         install_vsys = ( " ( "
325                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
326                     " ) "
327                     " || "
328                     " ( "
329                     "   cd ${SRC} ; "
330                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
331                     "   cd python-vsys ; "
332                     "   make all ; "
333                     "   sudo -S make install "
334                     " )" ) % ({
335                         "version": PYTHON_VSYS_VERSION
336                         })
337
338         install_passfd = ( " ( python -c 'import passfd' ) "
339                     " || "
340                     " ( "
341                     "   cd ${SRC} ; "
342                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
343                     "   cd python-passfd ; "
344                     "   make all ; "
345                     "   sudo -S make install "
346                     " )" )
347
348         return "%s ; %s" % ( install_vsys, install_passfd )
349
350     def valid_connection(self, guid):
351         # TODO: Validate!
352         return True
353