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