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