PlanetlabTap reads STOP from unix socket
[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 #       - Instead of doing an infinite loop, open a port for communication allowing
32 #           to pass the fd to another process
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", type = Types.Bool)
60         
61         snat = Attribute("snat", "Set SNAT=1", type = Types.Bool,
62                 flags = Flags.ReadOnly)
63         
64         pointopoint = Attribute("pointopoint", "Peer IP address", 
65                 flags = Flags.ReadOnly)
66
67         tear_down = Attribute("tearDown", "Bash script to be executed before " + \
68                 "releasing the resource",
69                 flags = Flags.ExecReadOnly)
70
71         cls._register_attribute(ip4)
72         cls._register_attribute(mac)
73         cls._register_attribute(prefix4)
74         cls._register_attribute(mtu)
75         cls._register_attribute(devname)
76         cls._register_attribute(up)
77         cls._register_attribute(snat)
78         cls._register_attribute(pointopoint)
79         cls._register_attribute(tear_down)
80
81     def __init__(self, ec, guid):
82         super(PlanetlabTap, self).__init__(ec, guid)
83         self._home = "tap-%s" % self.guid
84
85     @property
86     def node(self):
87         node = self.get_connected(PlanetlabNode.rtype())
88         if node: return node[0]
89         return None
90
91     def upload_sources(self):
92         depends = "mercurial make gcc"
93         self.set("depends", depends)
94
95         install = ( " ( "
96                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
97                     " ) "
98                     " ||"
99                     " ( "
100                     "   cd ${SRC} ; "
101                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
102                     "   cd python-vsys ; "
103                     "   make all ; "
104                     "   sudo -S make install "
105                     " )" ) % ({
106                         "version": PYTHON_VSYS_VERSION
107                         })
108
109         self.set("install", install)
110
111     def upload_start_command(self):
112         # upload tap-creation python script
113         pl_tap_create = os.path.join(os.path.dirname(__file__), "scripts",
114                 "pl-tap-create.py")
115         self.node.upload(pl_tap_create,
116                 os.path.join(self.app_home, "pl-vif-create.py"),
117                 overwrite = False)
118
119         # upload start.sh
120         start_command = self.replace_paths(self._start_command)
121         
122         self.info("Uploading command '%s'" % start_command)
123         
124         self.set("command", start_command)
125
126         self.node.upload(start_command,
127                 os.path.join(self.app_home, "start.sh"),
128                 text = True, 
129                 overwrite = False)
130
131         # upload tap-stop python script
132         pl_tap_stop = os.path.join(os.path.dirname(__file__), "scripts",
133                 "pl-tap-stop.py")
134         self.node.upload(pl_tap_stop,
135                 os.path.join(self.app_home, "pl-vif-stop.py"),
136                 overwrite = False)
137
138         # upload stop.sh script
139         stop_command = self.replace_paths(self._stop_command)
140         self.node.upload(stop_command,
141                 os.path.join(self.app_home, "stop.sh"),
142                 text = True, 
143                 overwrite = False)
144
145         # We want to make sure the device is up and running
146         # before the deploy finishes (so things will be ready
147         # before other stuff starts running).
148         # Run the command as a bash script in background,
149         # in the host ( but wait until the command has
150         # finished to continue )
151         self._run_in_background()
152         
153         # Retrive if_name
154         if_name = self.wait_if_name()
155         self.set("deviceName", if_name) 
156
157     def deploy(self):
158         if not self.node or self.node.state < ResourceState.PROVISIONED:
159             self.ec.schedule(reschedule_delay, self.deploy)
160         else:
161
162             try:
163                 self.discover()
164                 self.provision()
165             except:
166                 self.fail()
167                 raise
168  
169             self.debug("----- READY ---- ")
170             self._ready_time = tnow()
171             self._state = ResourceState.READY
172
173     def start(self):
174         if self._state == ResourceState.READY:
175             command = self.get("command")
176             self.info("Starting command '%s'" % command)
177
178             self._start_time = tnow()
179             self._state = ResourceState.STARTED
180         else:
181             msg = " Failed to execute command '%s'" % command
182             self.error(msg, out, err)
183             self._state = ResourceState.FAILED
184             raise RuntimeError, msg
185
186     def stop(self):
187         command = self.get('command') or ''
188         state = self.state
189         
190         if 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._stop_time = tnow()
198             self._state = ResourceState.STOPPED
199
200     @property
201     def state(self):
202         # First check if the ccnd has failed
203         state_check_delay = 0.5
204         if self._state == ResourceState.STARTED and \
205                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
206
207             if self.get("deviceName"):
208                 (out, err), proc = self.node.execute("ifconfig")
209
210                 if out.strip().find(self.get("deviceName")) == -1: 
211                     # tap is not running is not running (socket not found)
212                     self._state = ResourceState.FINISHED
213
214             self._last_state_check = tnow()
215
216         return self._state
217
218     def wait_if_name(self):
219         """ Waits until the if_name file for the command is generated, 
220             and returns the if_name for the devide """
221         if_name = None
222         delay = 1.0
223
224         for i in xrange(4):
225             (out, err), proc = self.node.check_output(self.run_home, "if_name")
226
227             if out:
228                 if_name = out.strip()
229                 break
230             else:
231                 time.sleep(delay)
232                 delay = delay * 1.5
233         else:
234             msg = "Couldn't retrieve if_name"
235             self.error(msg, out, err)
236             self.fail()
237             raise RuntimeError, msg
238
239         return if_name
240
241     @property
242     def _start_command(self):
243         command = ["sudo -S python ${APP_HOME}/pl-vif-create.py"]
244         
245         command.append("-t %s" % self.vif_type)
246         command.append("-a %s" % self.get("ip4"))
247         command.append("-n %d" % self.get("prefix4"))
248         command.append("-f %s " % self.if_name_file)
249         command.append("-S %s " % self.sock_name)
250         if self.get("snat") == True:
251             command.append("-s")
252         if self.get("pointopoint"):
253             command.append("-p %s" % self.get("pointopoint"))
254
255         return " ".join(command)
256
257     @property
258     def _stop_command(self):
259         command = ["sudo -S python ${APP_HOME}/pl-vif-stop.py"]
260         
261         command.append("-S %s " % self.sock_name)
262         return " ".join(command)
263
264     @property
265     def vif_type(self):
266         return "IFF_TAP"
267
268     @property
269     def if_name_file(self):
270         return os.path.join(self.run_home, "if_name")
271
272     @property
273     def sock_name(self):
274         return os.path.join(self.run_home, "tap.sock")
275
276     def valid_connection(self, guid):
277         # TODO: Validate!
278         return True
279