Adding help and background class atrributes to ResourceManager
[nepi.git] / src / nepi / resources / linux / udptunnel.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.util.sshfuncs import ProcStatus
25 from nepi.util.timefuncs import tnow, tdiffsec
26
27 import os
28 import socket
29 import time
30
31 @clsinit_copy
32 class UdpTunnel(LinuxApplication):
33     _rtype = "UdpTunnel"
34     _help = "Constructs a tunnel between two Linux endpoints using a UDP connection "
35     _backend = "linux"
36
37
38     @classmethod
39     def _register_attributes(cls):
40         cipher = Attribute("cipher",
41                "Cipher to encript communication. "
42                 "One of PLAIN, AES, Blowfish, DES, DES3. ",
43                 default = None,
44                 allowed = ["PLAIN", "AES", "Blowfish", "DES", "DES3"],
45                 type = Types.Enumerate, 
46                 flags = Flags.ExecReadOnly)
47
48         cipher_key = Attribute("cipherKey",
49                 "Specify a symmetric encryption key with which to protect "
50                 "packets across the tunnel. python-crypto must be installed "
51                 "on the system." ,
52                 flags = Flags.ExecReadOnly)
53
54         txqueuelen = Attribute("txQueueLen",
55                 "Specifies the interface's transmission queue length. "
56                 "Defaults to 1000. ", 
57                 type = Types.Integer, 
58                 flags = Flags.ExecReadOnly)
59
60         bwlimit = Attribute("bwLimit",
61                 "Specifies the interface's emulated bandwidth in bytes "
62                 "per second.",
63                 type = Types.Integer, 
64                 flags = Flags.ExecReadOnly)
65
66         cls._register_attribute(cipher)
67         cls._register_attribute(cipher_key)
68         cls._register_attribute(txqueuelen)
69         cls._register_attribute(bwlimit)
70
71     def __init__(self, ec, guid):
72         super(UdpTunnel, self).__init__(ec, guid)
73         self._home = "udp-tunnel-%s" % self.guid
74         self._pid1 = None
75         self._ppid1 = None
76         self._pid2 = None
77         self._ppid2 = None
78
79     def log_message(self, msg):
80         return " guid %d - tunnel %s - %s - %s " % (self.guid, 
81                 self.endpoint1.node.get("hostname"), 
82                 self.endpoint2.node.get("hostname"), 
83                 msg)
84
85     def get_endpoints(self):
86         """ Returns the list of RM that are endpoints to the tunnel 
87         """
88         connected = []
89         for guid in self.connections:
90             rm = self.ec.get_resource(guid)
91             if hasattr(rm, "udp_connect_command"):
92                 connected.append(rm)
93         return connected
94
95     @property
96     def endpoint1(self):
97         endpoints = self.get_endpoints()
98         if endpoints: return endpoints[0]
99         return None
100
101     @property
102     def endpoint2(self):
103         endpoints = self.get_endpoints()
104         if endpoints and len(endpoints) > 1: return endpoints[1]
105         return None
106
107     def app_home(self, endpoint):
108         return os.path.join(endpoint.node.exp_home, self._home)
109
110     def run_home(self, endpoint):
111         return os.path.join(self.app_home(endpoint), self.ec.run_id)
112
113     def udp_connect(self, endpoint, remote_ip):
114         # Get udp connect command
115         local_port_file = os.path.join(self.run_home(endpoint), 
116                 "local_port")
117         remote_port_file = os.path.join(self.run_home(endpoint), 
118                 "remote_port")
119         ret_file = os.path.join(self.run_home(endpoint), 
120                 "ret_file")
121         cipher = self.get("cipher")
122         cipher_key = self.get("cipherKey")
123         bwlimit = self.get("bwLimit")
124         txqueuelen = self.get("txQueueLen")
125         udp_connect_command = endpoint.udp_connect_command(
126                 remote_ip, local_port_file, remote_port_file,
127                 ret_file, cipher, cipher_key, bwlimit, txqueuelen)
128
129         # upload command to connect.sh script
130         shfile = os.path.join(self.app_home(endpoint), "udp-connect.sh")
131         endpoint.node.upload(udp_connect_command,
132                 shfile,
133                 text = True, 
134                 overwrite = False)
135
136         # invoke connect script
137         cmd = "bash %s" % shfile
138         (out, err), proc = endpoint.node.run(cmd, self.run_home(endpoint)) 
139              
140         # check if execution errors occurred
141         msg = " Failed to connect endpoints "
142         
143         if proc.poll():
144             self.fail()
145             self.error(msg, out, err)
146             raise RuntimeError, msg
147     
148         # Wait for pid file to be generated
149         pid, ppid = endpoint.node.wait_pid(self.run_home(endpoint))
150         
151         # If the process is not running, check for error information
152         # on the remote machine
153         if not pid or not ppid:
154             (out, err), proc = endpoint.node.check_errors(self.run_home(endpoint))
155             # Out is what was written in the stderr file
156             if err:
157                 self.fail()
158                 msg = " Failed to start command '%s' " % command
159                 self.error(msg, out, err)
160                 raise RuntimeError, msg
161
162         # wait until port is written to file
163         port = self.wait_local_port(endpoint)
164         return (port, pid, ppid)
165
166     def provision(self):
167         # create run dir for tunnel on each node 
168         self.endpoint1.node.mkdir(self.run_home(self.endpoint1))
169         self.endpoint2.node.mkdir(self.run_home(self.endpoint2))
170
171         # Invoke connect script in endpoint 1
172         remote_ip1 = socket.gethostbyname(self.endpoint2.node.get("hostname"))
173         (port1, self._pid1, self._ppid1) = self.udp_connect(self.endpoint1,
174                 remote_ip1)
175
176         # Invoke connect script in endpoint 2
177         remote_ip2 = socket.gethostbyname(self.endpoint1.node.get("hostname"))
178         (port2, self._pid2, self._ppid2) = self.udp_connect(self.endpoint2,
179                 remote_ip2)
180
181         # upload file with port 2 to endpoint 1
182         self.upload_remote_port(self.endpoint1, port2)
183         
184         # upload file with port 1 to endpoint 2
185         self.upload_remote_port(self.endpoint2, port1)
186
187         # check if connection was successful on both sides
188         self.wait_result(self.endpoint1)
189         self.wait_result(self.endpoint2)
190        
191         self.info("Provisioning finished")
192  
193         self.set_provisioned()
194
195     def deploy(self):
196         if (not self.endpoint1 or self.endpoint1.state < ResourceState.READY) or \
197             (not self.endpoint2 or self.endpoint2.state < ResourceState.READY):
198             self.ec.schedule(reschedule_delay, self.deploy)
199         else:
200             try:
201                 self.discover()
202                 self.provision()
203             except:
204                 self.fail()
205                 raise
206  
207             self.debug("----- READY ---- ")
208             self.set_ready()
209
210     def start(self):
211         if self.state == ResourceState.READY:
212             command = self.get("command")
213             self.info("Starting command '%s'" % command)
214             
215             self.set_started()
216         else:
217             msg = " Failed to execute command '%s'" % command
218             self.error(msg, out, err)
219             self.fail()
220             raise RuntimeError, msg
221
222     def stop(self):
223         """ Stops application execution
224         """
225         if self.state == ResourceState.STARTED:
226             self.info("Stopping tunnel")
227     
228             # Only try to kill the process if the pid and ppid
229             # were retrieved
230             if self._pid1 and self._ppid1 and self._pid2 and self._ppid2:
231                 (out1, err1), proc1 = self.endpoint1.node.kill(self._pid1,
232                         self._ppid1, sudo = True) 
233                 (out2, err2), proc2 = self.endpoint2.node.kill(self._pid2, 
234                         self._ppid2, sudo = True) 
235
236                 if err1 or err2 or proc1.poll() or proc2.poll():
237                     # check if execution errors occurred
238                     msg = " Failed to STOP tunnel"
239                     self.error(msg, err1, err2)
240                     self.fail()
241
242         if self.state == ResourceState.STARTED:
243             self.set_stopped()
244
245     @property
246     def state(self):
247         """ Returns the state of the application
248         """
249         if self._state == ResourceState.STARTED:
250             # In order to avoid overwhelming the remote host and
251             # the local processor with too many ssh queries, the state is only
252             # requested every 'state_check_delay' seconds.
253             state_check_delay = 0.5
254             if tdiffsec(tnow(), self._last_state_check) > state_check_delay:
255                 if self._pid1 and self._ppid1 and self._pid2 and self._ppid2:
256                     # Make sure the process is still running in background
257                     # No execution errors occurred. Make sure the background
258                     # process with the recorded pid is still running.
259                     status1 = self.endpoint1.node.status(self._pid1, self._ppid1)
260                     status2 = self.endpoint2.node.status(self._pid2, self._ppid2)
261
262                     if status1 == ProcStatus.FINISHED and \
263                             status2 == ProcStatus.FINISHED:
264
265                         # check if execution errors occurred
266                         (out1, err1), proc1 = self.endpoint1.node.check_errors(
267                                 self.run_home(self.endpoint1))
268
269                         (out2, err2), proc2 = self.endpoint2.node.check_errors(
270                                 self.run_home(self.endpoint2))
271
272                         if err1 or err2: 
273                             msg = "Error occurred in tunnel"
274                             self.error(msg, err1, err2)
275                             self.fail()
276                         else:
277                             self.set_finished()
278
279                 self._last_state_check = tnow()
280
281         return self._state
282
283     def wait_local_port(self, endpoint):
284         """ Waits until the local_port file for the endpoint is generated, 
285         and returns the port number 
286         
287         """
288         return self.wait_file(endpoint, "local_port")
289
290     def wait_result(self, endpoint):
291         """ Waits until the return code file for the endpoint is generated 
292         
293         """ 
294         return self.wait_file(endpoint, "ret_file")
295  
296     def wait_file(self, endpoint, filename):
297         """ Waits until file on endpoint is generated """
298         result = None
299         delay = 1.0
300
301         for i in xrange(4):
302             (out, err), proc = endpoint.node.check_output(
303                     self.run_home(endpoint), filename)
304
305             if out:
306                 result = out.strip()
307                 break
308             else:
309                 time.sleep(delay)
310                 delay = delay * 1.5
311         else:
312             msg = "Couldn't retrieve %s" % filename
313             self.error(msg, out, err)
314             self.fail()
315             raise RuntimeError, msg
316
317         return result
318
319     def upload_remote_port(self, endpoint, port):
320         # upload remote port number to file
321         port = "%s\n" % port
322         endpoint.node.upload(port,
323                 os.path.join(self.run_home(endpoint), "remote_port"),
324                 text = True, 
325                 overwrite = False)
326
327     def valid_connection(self, guid):
328         # TODO: Validate!
329         return True
330