Adding working UdpTunnel for Planetlab and Linux
[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 ResourceManager, 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: - routes!!!
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
40     @classmethod
41     def _register_attributes(cls):
42         ip4 = Attribute("ip4", "IPv4 Address",
43               flags = Flags.ExecReadOnly)
44
45         mac = Attribute("mac", "MAC Address",
46                 flags = Flags.ExecReadOnly)
47
48         prefix4 = Attribute("prefix4", "IPv4 network prefix",
49                 type = Types.Integer,
50                 flags = Flags.ExecReadOnly)
51
52         mtu = Attribute("mtu", "Maximum transmition unit for device",
53                 type = Types.Integer)
54
55         devname = Attribute("deviceName", 
56                 "Name of the network interface (e.g. eth0, wlan0, etc)",
57                 flags = Flags.ReadOnly)
58
59         up = Attribute("up", "Link up", 
60                 type = Types.Bool)
61         
62         snat = Attribute("snat", "Set SNAT=1", 
63                 type = Types.Bool,
64                 flags = Flags.ExecReadOnly)
65         
66         pointopoint = Attribute("pointopoint", "Peer IP address", 
67                 flags = Flags.ExecReadOnly)
68
69         tear_down = Attribute("tearDown", "Bash script to be executed before " + \
70                 "releasing the resource",
71                 flags = Flags.ExecReadOnly)
72
73         cls._register_attribute(ip4)
74         cls._register_attribute(mac)
75         cls._register_attribute(prefix4)
76         cls._register_attribute(mtu)
77         cls._register_attribute(devname)
78         cls._register_attribute(up)
79         cls._register_attribute(snat)
80         cls._register_attribute(pointopoint)
81         cls._register_attribute(tear_down)
82
83     def __init__(self, ec, guid):
84         super(PlanetlabTap, self).__init__(ec, guid)
85         self._home = "tap-%s" % self.guid
86
87     @property
88     def node(self):
89         node = self.get_connected(PlanetlabNode.rtype())
90         if node: return node[0]
91         return None
92
93     def upload_sources(self):
94         # upload vif-creation python script
95         pl_vif_create = os.path.join(os.path.dirname(__file__), "scripts",
96                 "pl-vif-create.py")
97
98         self.node.upload(pl_vif_create,
99                 os.path.join(self.node.src_dir, "pl-vif-create.py"),
100                 overwrite = False)
101
102         # upload vif-stop python script
103         pl_vif_stop = os.path.join(os.path.dirname(__file__), "scripts",
104                 "pl-vif-stop.py")
105
106         self.node.upload(pl_vif_stop,
107                 os.path.join(self.node.src_dir, "pl-vif-stop.py"),
108                 overwrite = False)
109
110         # upload vif-connect python script
111         pl_vif_connect = os.path.join(os.path.dirname(__file__), "scripts",
112                 "pl-vif-udp-connect.py")
113
114         self.node.upload(pl_vif_connect,
115                 os.path.join(self.node.src_dir, "pl-vif-udp-connect.py"),
116                 overwrite = False)
117
118         # upload tun-connect python script
119         tunchannel = os.path.join(os.path.dirname(__file__), "..", "linux",
120                 "scripts", "tunchannel.py")
121
122         self.node.upload(tunchannel,
123                 os.path.join(self.node.src_dir, "tunchannel.py"),
124                 overwrite = False)
125
126         # upload stop.sh script
127         stop_command = self.replace_paths(self._stop_command)
128         self.node.upload(stop_command,
129                 os.path.join(self.app_home, "stop.sh"),
130                 text = True, 
131                 overwrite = False)
132
133     def upload_start_command(self):
134         super(PlanetlabTap, self).upload_start_command()
135
136         # We want to make sure the device is up and running
137         # before the deploy finishes (so things will be ready
138         # before other stuff starts running).
139         # Run the command as a bash script in background,
140         # in the host ( but wait until the command has
141         # finished to continue )
142         self._run_in_background()
143         
144         # Retrive if_name
145         if_name = self._wait_if_name()
146         self.set("deviceName", if_name) 
147
148     def deploy(self):
149         if not self.node or self.node.state < ResourceState.PROVISIONED:
150             self.ec.schedule(reschedule_delay, self.deploy)
151         else:
152             if not self.get("command"):
153                 self.set("command", self._start_command)
154
155             if not self.get("depends"):
156                 self.set("depends", self._dependencies)
157
158             if not self.get("install"):
159                 self.set("install", self._install)
160
161             try:
162                 self.discover()
163                 self.provision()
164             except:
165                 self.fail()
166                 raise
167  
168             self.debug("----- READY ---- ")
169             self._ready_time = tnow()
170             self._state = ResourceState.READY
171
172     def start(self):
173         if self._state == ResourceState.READY:
174             command = self.get("command")
175             self.info("Starting command '%s'" % command)
176
177             self._start_time = tnow()
178             self._state = ResourceState.STARTED
179         else:
180             msg = " Failed to execute command '%s'" % command
181             self.error(msg, out, err)
182             self._state = ResourceState.FAILED
183             raise RuntimeError, msg
184
185     def stop(self):
186         command = self.get('command') or ''
187         state = self.state
188         
189         if state == ResourceState.STARTED:
190             self.info("Stopping command '%s'" % command)
191
192             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
193             (out, err), proc = self.execute_command(command,
194                     blocking = True)
195
196             self._stop_time = tnow()
197             self._state = ResourceState.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._state = ResourceState.FINISHED
212
213             self._last_state_check = tnow()
214
215         return self._state
216
217     def _wait_if_name(self):
218         """ Waits until the if_name file for the command is generated, 
219             and returns the if_name for the device """
220         if_name = None
221         delay = 1.0
222
223         for i in xrange(4):
224             (out, err), proc = self.node.check_output(self.run_home, "if_name")
225
226             if out:
227                 if_name = out.strip()
228                 break
229             else:
230                 time.sleep(delay)
231                 delay = delay * 1.5
232         else:
233             msg = "Couldn't retrieve if_name"
234             self.error(msg, out, err)
235             self.fail()
236             raise RuntimeError, msg
237
238         return if_name
239
240     def udp_connect_command(self, remote_ip, local_port_file, 
241             remote_port_file, ret_file):
242         command = ["sudo -S "]
243         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
244         command.append("python ${SRC}/pl-vif-udp-connect.py")
245         command.append("-t %s" % self.vif_type)
246         command.append("-S %s " % self.sock_name)
247         command.append("-l %s " % local_port_file)
248         command.append("-r %s " % remote_port_file)
249         command.append("-H %s " % remote_ip)
250         command.append("-R %s " % ret_file)
251
252         command = " ".join(command)
253         command = self.replace_paths(command)
254         return command
255
256     @property
257     def _start_command(self):
258         command = ["sudo -S python ${SRC}/pl-vif-create.py"]
259         
260         command.append("-t %s" % self.vif_type)
261         command.append("-a %s" % self.get("ip4"))
262         command.append("-n %d" % self.get("prefix4"))
263         command.append("-f %s " % self.if_name_file)
264         command.append("-S %s " % self.sock_name)
265         if self.get("snat") == True:
266             command.append("-s")
267         if self.get("pointopoint"):
268             command.append("-p %s" % self.get("pointopoint"))
269
270         return " ".join(command)
271
272     @property
273     def _stop_command(self):
274         command = ["sudo -S python ${SRC}/pl-vif-stop.py"]
275         
276         command.append("-S %s " % self.sock_name)
277         return " ".join(command)
278
279     @property
280     def vif_type(self):
281         return "IFF_TAP"
282
283     @property
284     def if_name_file(self):
285         return os.path.join(self.run_home, "if_name")
286
287     @property
288     def sock_name(self):
289         return os.path.join(self.run_home, "tap.sock")
290
291     @property
292     def _dependencies(self):
293         return "mercurial make gcc"
294
295     @property
296     def _install(self):
297         # Install python-vsys and python-passfd
298         install_vsys = ( " ( "
299                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
300                     " ) "
301                     " || "
302                     " ( "
303                     "   cd ${SRC} ; "
304                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
305                     "   cd python-vsys ; "
306                     "   make all ; "
307                     "   sudo -S make install "
308                     " )" ) % ({
309                         "version": PYTHON_VSYS_VERSION
310                         })
311
312         install_passfd = ( " ( python -c 'import passfd' ) "
313                     " || "
314                     " ( "
315                     "   cd ${SRC} ; "
316                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
317                     "   cd python-passfd ; "
318                     "   make all ; "
319                     "   sudo -S make install "
320                     " )" )
321
322         return "%s ; %s" % ( install_vsys, install_passfd )
323
324     def valid_connection(self, guid):
325         # TODO: Validate!
326         return True
327