Added GRE functionallity to PlanetLabTAP
[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.tunnel import LinuxTunnel
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 LinuxUdpTunnel(LinuxTunnel):
33     _rtype = "LinuxUdpTunnel"
34     _help = "Constructs a tunnel between two Linux endpoints using a UDP connection "
35     _backend = "linux"
36
37     @classmethod
38     def _register_attributes(cls):
39         cipher = Attribute("cipher",
40                "Cipher to encript communication. "
41                 "One of PLAIN, AES, Blowfish, DES, DES3. ",
42                 default = None,
43                 allowed = ["PLAIN", "AES", "Blowfish", "DES", "DES3"],
44                 type = Types.Enumerate, 
45                 flags = Flags.Design)
46
47         cipher_key = Attribute("cipherKey",
48                 "Specify a symmetric encryption key with which to protect "
49                 "packets across the tunnel. python-crypto must be installed "
50                 "on the system." ,
51                 flags = Flags.Design)
52
53         txqueuelen = Attribute("txQueueLen",
54                 "Specifies the interface's transmission queue length. "
55                 "Defaults to 1000. ", 
56                 type = Types.Integer, 
57                 flags = Flags.Design)
58
59         bwlimit = Attribute("bwLimit",
60                 "Specifies the interface's emulated bandwidth in bytes "
61                 "per second.",
62                 type = Types.Integer, 
63                 flags = Flags.Design)
64
65         cls._register_attribute(cipher)
66         cls._register_attribute(cipher_key)
67         cls._register_attribute(txqueuelen)
68         cls._register_attribute(bwlimit)
69
70     def __init__(self, ec, guid):
71         super(LinuxUdpTunnel, self).__init__(ec, guid)
72         self._home = "udp-tunnel-%s" % self.guid
73         self._pids = dict()
74
75     def log_message(self, msg):
76         return " guid %d - udptunnel %s - %s - %s " % (self.guid, 
77                 self.endpoint1.node.get("hostname"), 
78                 self.endpoint2.node.get("hostname"), 
79                 msg)
80
81     def get_endpoints(self):
82         """ Returns the list of RM that are endpoints to the tunnel 
83         """
84         connected = []
85         for guid in self.connections:
86             rm = self.ec.get_resource(guid)
87             if hasattr(rm, "udp_connect_command"):
88                 connected.append(rm)
89         return connected
90
91     def initiate_connection(self, endpoint, remote_endpoint):
92         cipher = self.get("cipher")
93         cipher_key = self.get("cipherKey")
94         bwlimit = self.get("bwLimit")
95         txqueuelen = self.get("txQueueLen")
96        
97         # Return the command to execute to initiate the connection to the
98         # other endpoint
99         connection_run_home = self.run_home(endpoint)
100         udp_connect_command = endpoint.udp_connect_command(
101                 remote_endpoint, connection_run_home,
102                 cipher, cipher_key, bwlimit, txqueuelen)
103
104         # upload command to connect.sh script
105         shfile = os.path.join(self.app_home(endpoint), "udp-connect.sh")
106         endpoint.node.upload(udp_connect_command,
107                 shfile,
108                 text = True, 
109                 overwrite = False)
110
111         # invoke connect script
112         cmd = "bash %s" % shfile
113         (out, err), proc = endpoint.node.run(cmd, self.run_home(endpoint)) 
114              
115         # check if execution errors occurred
116         msg = "Failed to connect endpoints "
117         
118         if proc.poll():
119             self.error(msg, out, err)
120             raise RuntimeError, msg
121     
122         # Wait for pid file to be generated
123         pid, ppid = endpoint.node.wait_pid(self.run_home(endpoint))
124         
125         # If the process is not running, check for error information
126         # on the remote machine
127         if not pid or not ppid:
128             (out, err), proc = endpoint.node.check_errors(self.run_home(endpoint))
129             # Out is what was written in the stderr file
130             if err:
131                 msg = " Failed to start command '%s' " % command
132                 self.error(msg, out, err)
133                 raise RuntimeError, msg
134
135         # wait until port is written to file
136         port = self.wait_local_port(endpoint)
137
138         self._pids[endpoint] = (pid, ppid)
139
140         return port
141
142     def establish_connection(self, endpoint, remote_endpoint, port):
143         self.upload_remote_port(endpoint, port)
144
145     def verify_connection(self, endpoint, remote_endpoint):
146         self.wait_result(endpoint)
147
148     def terminate_connection(self, endpoint, remote_endpoint):
149         pid, ppid = self._pids[endpoint]
150
151         if pid and ppid:
152             (out, err), proc = endpoint.node.kill(pid, ppid, 
153                     sudo = True) 
154
155             # check if execution errors occurred
156             if proc.poll() and err:
157                 msg = " Failed to STOP tunnel"
158                 self.error(msg, out, err)
159                 raise RuntimeError, msg
160
161     def check_state_connection(self):
162         # Make sure the process is still running in background
163         # No execution errors occurred. Make sure the background
164         # process with the recorded pid is still running.
165         pid1, ppid1 = self._pids[self.endpoint1]
166         pid2, ppid2 = self._pids[self.endpoint2]
167
168         status1 = self.endpoint1.node.status(pid1, ppid1)
169         status2 = self.endpoint2.node.status(pid2, ppid2)
170
171         if status1 == ProcStatus.FINISHED and \
172                 status2 == ProcStatus.FINISHED:
173
174             # check if execution errors occurred
175             (out1, err1), proc1 = self.endpoint1.node.check_errors(
176                     self.run_home(self.endpoint1))
177
178             (out2, err2), proc2 = self.endpoint2.node.check_errors(
179                     self.run_home(self.endpoint2))
180
181             if err1 or err2: 
182                 msg = "Error occurred in tunnel"
183                 self.error(msg, err1, err2)
184                 self.fail()
185             else:
186                 self.set_stopped()
187
188     def wait_local_port(self, endpoint):
189         """ Waits until the local_port file for the endpoint is generated, 
190         and returns the port number 
191         
192         """
193         return self.wait_file(endpoint, "local_port")
194
195     def wait_result(self, endpoint):
196         """ Waits until the return code file for the endpoint is generated 
197         
198         """ 
199         return self.wait_file(endpoint, "ret_file")
200  
201     def wait_file(self, endpoint, filename):
202         """ Waits until file on endpoint is generated """
203         result = None
204         delay = 1.0
205
206         for i in xrange(20):
207             (out, err), proc = endpoint.node.check_output(
208                     self.run_home(endpoint), filename)
209
210             if out:
211                 result = out.strip()
212                 break
213             else:
214                 time.sleep(delay)
215                 delay = delay * 1.5
216         else:
217             msg = "Couldn't retrieve %s" % filename
218             self.error(msg, out, err)
219             raise RuntimeError, msg
220
221         return result
222
223     def upload_remote_port(self, endpoint, port):
224         # upload remote port number to file
225         port = "%s\n" % port
226         endpoint.node.upload(port,
227                 os.path.join(self.run_home(endpoint), "remote_port"),
228                 text = True, 
229                 overwrite = False)
230
231