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