39567b3f6a4a4775d2d92081a9999c40864b60dd
[nepi.git] / src / nepi / resources / planetlab / openvswitch / ovs.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 #         Alexandros Kouvakas <alexandros.kouvakas@inria.fr>
20
21
22 from nepi.execution.resource import ResourceManager, clsinit_copy, \
23         ResourceState
24 from nepi.execution.attribute import Attribute, Flags
25 from nepi.resources.planetlab.node import PlanetlabNode        
26 from nepi.resources.linux.application import LinuxApplication
27 import os
28
29 reschedule_delay = "0.5s"
30
31 @clsinit_copy                    
32 class OVSSwitch(LinuxApplication):
33     """
34     .. class:: Class Args :
35       
36         :param ec: The Experiment controller
37         :type ec: ExperimentController
38         :param guid: guid of the RM
39         :type guid: int
40
41     """
42
43     _rtype = "OVSSwitch"
44     _help = "Runs an OpenVSwitch on a PlanetLab host"
45     _backend = "planetlab"
46
47     _authorized_connections = ["PlanetlabNode", "OVSPort", "LinuxNode"]       
48
49     @classmethod
50     def _register_attributes(cls):
51         """ Register the attributes of OVSSwitch RM 
52
53         """
54         bridge_name = Attribute("bridge_name", "Name of the switch/bridge",
55                 flags = Flags.Design)   
56         virtual_ip_pref = Attribute("virtual_ip_pref", "Virtual IP/PREFIX of the switch",
57                 flags = Flags.Design)   
58         controller_ip = Attribute("controller_ip", "IP of the controller",
59                 flags = Flags.Design)   
60         controller_port = Attribute("controller_port", "Port of the controller",
61                 flags = Flags.Design)   
62
63         cls._register_attribute(bridge_name)
64         cls._register_attribute(virtual_ip_pref)
65         cls._register_attribute(controller_ip)
66         cls._register_attribute(controller_port)
67
68     def __init__(self, ec, guid):
69         """
70         :param ec: The Experiment controller
71         :type ec: ExperimentController
72         :param guid: guid of the RM
73         :type guid: int
74     
75         """
76         super(OVSSwitch, self).__init__(ec, guid)
77         self._home = "ovsswitch-%s" % self.guid
78         self._checks = "ovsChecks-%s" % self.guid
79
80     @property
81     def node(self):
82         """ Node wthat run the switch
83         """
84         node = self.get_connected(PlanetlabNode.get_rtype())
85         if node: return node[0]
86         return None
87
88     def log_message(self, msg):
89         return " guid %d - OVSSwitch - %s " % (self.guid, msg)
90
91     @property
92     def ovs_home(self):
93         return os.path.join(self.node.exp_home, self._home)
94
95     @property
96     def ovs_checks(self):
97         return os.path.join(self.ovs_home, self._checks)
98
99     def valid_connection(self, guid):
100         """ Check if the connection with the guid in parameter is possible. Only meaningful connections are allowed.
101
102         :param guid: Guid of the current RM
103         :type guid: int
104         :rtype:  Boolean
105
106         """
107         rm = self.ec.get_resource(guid)
108         if rm.get_rtype() in self._authorized_connections:
109             msg = "Connection between %s %s and %s %s accepted" % \
110                 (self.get_rtype(), self._guid, rm.get_rtype(), guid)
111             self.debug(msg)
112             return True
113         msg = "Connection between %s %s and %s %s refused" % \
114              (self.get_rtype(), self._guid, rm.get_rtype(), guid)
115         self.debug(msg)
116         return False
117
118     def do_provision(self):
119         """ Create the different OVS folder.
120         """
121
122         # create home dir for ovs
123         self.node.mkdir(self.ovs_home)
124         # create dir for ovs checks
125         self.node.mkdir(self.ovs_checks)
126         
127         super(OVSSwitch, self).do_provision()
128                                 
129     def do_deploy(self):
130         """ Deploy the OVS Switch : Turn on the server, create the bridges
131             and assign the controller
132         """
133
134         if not self.node or self.node.state < ResourceState.READY:
135             self.ec.schedule(reschedule_delay, self.deploy)
136             return
137
138         self.do_discover()
139         self.do_provision()
140
141         self.check_sliver_ovs()
142         self.servers_on()
143         self.create_bridge()
144         self.assign_controller()
145         self.ovs_status()
146             
147         super(OVSSwitch, self).do_deploy()
148
149     def check_sliver_ovs(self):  
150         """ Check if sliver-ovs exists. If it does not exist, the execution is stopped
151         """
152
153         cmd = "compgen -c | grep sliver-ovs"                    
154         out = err = ""
155
156         (out,err), proc = self.node.run_and_wait(cmd, self.ovs_checks, 
157                     shfile = "check_cmd.sh",
158                 pidfile = "check_cmd_pidfile",
159                 ecodefile = "check_cmd_exitcode", 
160                 sudo = True, 
161                 stdout = "check_cmd_stdout", 
162                 stderr = "check_cmd_stderr")
163
164         (out, err), proc = self.node.check_output(self.ovs_checks, 'check_cmd_exitcode')
165         
166         if out != "0\n":
167             msg = "Command sliver-ovs does not exist on the VM"          
168             self.debug(msg)
169             raise RuntimeError, msg
170
171         msg = "Command sliver-ovs exists" 
172         self.debug(msg)
173
174     def servers_on(self):
175         """ Start the openvswitch servers and check it
176         """
177
178         # Start the server
179         command = "sliver-ovs start"            
180         out = err = ""                                                                  
181         (out, err), proc = self.node.run_and_wait(command, self.ovs_checks,   
182                 shfile = "start_srv.sh",
183                 pidfile = "start_srv_pidfile",
184                 ecodefile = "start_srv_exitcode", 
185                 sudo = True, 
186                 raise_on_error = True,
187                 stdout = "start_srv_stdout", 
188                 stderr = "start_srv_stderr")
189         (out, err), proc = self.node.check_output(self.ovs_checks, 'start_srv_exitcode')
190
191         if out != "0\n":
192             self.error("Servers have not started")
193             raise RuntimeError, msg     
194                                 
195         # Check if the servers are running or not
196         cmd = "ps -A | grep ovsdb-server"
197         out = err = ""
198         (out, err), proc = self.node.run_and_wait(cmd, self.ovs_checks, 
199                 shfile = "status_srv.sh",
200                 pidfile = "status_srv_pidfile",
201                 ecodefile = "status_srv_exitcode", 
202                 sudo = True, 
203                 stdout = "status_srv_stdout", 
204                 stderr = "status_srv_stderr")
205         (out, err), proc = self.node.check_output(self.ovs_checks, 'status_srv_exitcode')
206         
207         if out != "0\n":
208             msg = "Servers are not running"
209             self.error(msg)
210             raise RuntimeError, msg
211         
212         self.info("Server OVS Started Correctly")  
213
214     def create_bridge(self):
215         """ Create the bridge/switch and check error during SSH connection
216         """
217         # TODO: Check if previous bridge exist and delete them. Use ovs-vsctl list-br
218         # TODO: Add check for virtual_ip belonging to vsys_tag
219
220         
221         if not (self.get("bridge_name") and self.get("virtual_ip_pref")):
222             msg = "No assignment in one or both attributes"
223             self.error(msg)
224             raise AttributeError, msg
225
226         cmd = "sliver-ovs create-bridge '%s' '%s'" %\
227             (self.get("bridge_name"), self.get("virtual_ip_pref")) 
228         out = err = ""
229         (out, err), proc = self.node.run_and_wait(cmd, self.ovs_checks,
230                 shfile = "create_br.sh",
231                 pidfile = "create_br_pidfile",
232                 ecodefile = "create_br_exitcode", 
233                 sudo = True, 
234                 stdout = "create_br_stdout", 
235                 stderr = "create_br_stderr") 
236         (out, err), proc = self.node.check_output(self.ovs_checks, 'create_br_exitcode')
237
238         if out != "0\n":
239             msg = "No such pltap netdev\novs-appctl: ovs-vswitchd: server returned an error"
240             self.error(msg)                     
241             raise RuntimeError, msg
242
243         self.info(" Bridge %s Created and Assigned to %s" %\
244             (self.get("bridge_name"), self.get("virtual_ip_pref")) )
245           
246
247     def assign_controller(self):
248         """ Set the controller IP
249         """
250
251         if not (self.get("controller_ip") and self.get("controller_port")):
252             msg = "No assignment in one or both attributes"
253             self.error(msg)
254             raise AttributeError, msg
255
256         cmd = "ovs-vsctl set-controller %s tcp:%s:%s" %\
257             (self.get("bridge_name"), self.get("controller_ip"), self.get("controller_port"))
258         out = err = ""
259         (out, err), proc = self.node.run(cmd, self.ovs_checks,
260                 sudo = True, 
261                 stdout = "stdout", 
262                 stderr = "stderr")
263
264         if err != "":
265             msg = "SSH connection in the method assign_controller"
266             self.error(msg)
267             raise RuntimeError, msg
268
269         self.info("Controller assigned to the bridge %s" % self.get("bridge_name"))
270             
271     def ovs_status(self):
272         """ Print the status of the bridge                              
273         """
274
275         cmd = "sliver-ovs show | tail -n +2"
276         out = err = ""
277         (out, err), proc = self.node.run_and_wait(cmd, self.ovs_home,
278                 sudo = True, 
279                 stdout = "show_stdout", 
280                 stderr = "show_stderr") 
281         (out, err), proc = self.node.check_output(self.ovs_home, 'show_stdout')
282         
283         if out == "":
284             msg = "Error when checking the status of the OpenVswitch"
285             self.error(msg)
286             raise RuntimeError, msg
287         
288         self.debug(out)
289
290     def do_release(self):
291         """ Delete the bridge and close the server.  
292
293           .. note : It need to wait for the others RM (OVSPort and OVSTunnel)
294         to be released before releasing itself
295
296         """
297
298         from nepi.resources.planetlab.openvswitch.ovsport import OVSPort
299         rm = self.get_connected(OVSPort.get_rtype())
300
301         if rm[0].state < ResourceState.RELEASED:
302             self.ec.schedule(reschedule_delay, self.release)
303             return 
304             
305         cmd = "sliver-ovs del-bridge %s" % self.get('bridge_name')
306         (out, err), proc = self.node.run(cmd, self.ovs_checks,
307                 sudo = True)
308
309         cmd = "sliver-ovs stop"
310         (out, err), proc = self.node.run(cmd, self.ovs_checks,
311                 sudo = True)
312
313         msg = "Deleting the bridge %s" % self.get('bridge_name')
314         self.info(msg)
315         
316         if proc.poll():
317             self.error(msg, out, err)
318             raise RuntimeError, msg
319
320         super(OVSSwitch, self).do_release()
321