merged ex_shutdown into nepi-3-dev
[nepi.git] / src / nepi / resources / omf / application.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 #         Julien Tribino <julien.tribino@inria.fr>
20
21 from nepi.execution.resource import ResourceManager, clsinit_copy, \
22         ResourceState, reschedule_delay, failtrap
23 from nepi.execution.attribute import Attribute, Flags 
24 from nepi.resources.omf.omf_resource import ResourceGateway, OMFResource
25 from nepi.resources.omf.node import OMFNode
26 from nepi.resources.omf.omf_api import OMFAPIFactory
27
28 @clsinit_copy
29 class OMFApplication(OMFResource):
30     """
31     .. class:: Class Args :
32       
33         :param ec: The Experiment controller
34         :type ec: ExperimentController
35         :param guid: guid of the RM
36         :type guid: int
37         :param creds: Credentials to communicate with the rm (XmppClient)
38         :type creds: dict
39
40     .. note::
41
42        This class is used only by the Experiment Controller through the 
43        Resource Factory
44
45     """
46     _rtype = "OMFApplication"
47     _authorized_connections = ["OMFNode"]
48
49     @classmethod
50     def _register_attributes(cls):
51         """ Register the attributes of an OMF application
52
53         """
54         appid = Attribute("appid", "Name of the application")
55         path = Attribute("path", "Path of the application")
56         args = Attribute("args", "Argument of the application")
57         env = Attribute("env", "Environnement variable of the application")
58         stdin = Attribute("stdin", "Input of the application", default = "")
59         cls._register_attribute(appid)
60         cls._register_attribute(path)
61         cls._register_attribute(args)
62         cls._register_attribute(env)
63         cls._register_attribute(stdin)
64
65     def __init__(self, ec, guid):
66         """
67         :param ec: The Experiment controller
68         :type ec: ExperimentController
69         :param guid: guid of the RM
70         :type guid: int
71         :param creds: Credentials to communicate with the rm (XmppClient for OMF)
72         :type creds: dict
73
74         """
75         super(OMFApplication, self).__init__(ec, guid)
76
77         self.set('appid', "")
78         self.set('path', "")
79         self.set('args', "")
80         self.set('env', "")
81
82         self._node = None
83
84         self._omf_api = None
85
86         self.add_set_hook()
87
88     @property
89     def exp_id(self):
90         return self.ec.exp_id
91
92     @property
93     def node(self):
94         rm_list = self.get_connected(OMFNode.rtype())
95         if rm_list: return rm_list[0]
96         return None
97
98     def stdin_hook(self, old_value, new_value):
99         self._omf_api.send_stdin(self.node.get('hostname'), new_value, self.get('appid'))
100         return new_value
101
102     def add_set_hook(self):
103         attr = self._attrs["stdin"]
104         attr.set_hook = self.stdin_hook
105
106     def valid_connection(self, guid):
107         """ Check if the connection with the guid in parameter is possible. 
108         Only meaningful connections are allowed.
109
110         :param guid: Guid of RM it will be connected
111         :type guid: int
112         :rtype:  Boolean
113
114         """
115         rm = self.ec.get_resource(guid)
116         if rm.rtype() not in self._authorized_connections:
117             msg = ("Connection between %s %s and %s %s refused: "
118                     "An Application can be connected only to a Node" ) % \
119                 (self.rtype(), self._guid, rm.rtype(), guid)
120             self.debug(msg)
121
122             return False
123
124         elif len(self.connections) != 0 :
125             msg = ("Connection between %s %s and %s %s refused: "
126                     "This Application is already connected" ) % \
127                 (self.rtype(), self._guid, rm.rtype(), guid)
128             self.debug(msg)
129
130             return False
131
132         else :
133             msg = "Connection between %s %s and %s %s accepted" % (
134                     self.rtype(), self._guid, rm.rtype(), guid)
135             self.debug(msg)
136
137             return True
138
139     @failtrap
140     def deploy(self):
141         """ Deploy the RM. It means nothing special for an application 
142         for now (later it will be upload sources, ...)
143         It becomes DEPLOYED after getting the xmpp client.
144
145         """
146         if not self._omf_api :
147             self._omf_api = OMFAPIFactory.get_api(self.get('xmppSlice'), 
148                 self.get('xmppHost'), self.get('xmppPort'), 
149                 self.get('xmppPassword'), exp_id = self.exp_id)
150
151         if not self._omf_api :
152             msg = "Credentials are not initialzed. XMPP Connections impossible"
153             self.error(msg)
154             raise RuntimeError, msg
155
156         super(OMFApplication, self).deploy()
157
158     @failtrap
159     def start(self):
160         """ Start the RM. It means : Send Xmpp Message Using OMF protocol 
161          to execute the application. 
162          It becomes STARTED before the messages are sent (for coordination)
163
164         """
165         if not (self.get('appid') and self.get('path')) :
166             msg = "Application's information are not initialized"
167             self.error(msg)
168             raise RuntimeError, msg
169
170         if not self.get('args'):
171             self.set('args', " ")
172         if not self.get('env'):
173             self.set('env', " ")
174
175         # Some information to check the information in parameter
176         msg = " " + self.rtype() + " ( Guid : " + str(self._guid) +") : " + \
177             self.get('appid') + " : " + self.get('path') + " : " + \
178             self.get('args') + " : " + self.get('env')
179         self.info(msg)
180
181         try:
182             self._omf_api.execute(self.node.get('hostname'),self.get('appid'), \
183                 self.get('args'), self.get('path'), self.get('env'))
184         except AttributeError:
185             msg = "Credentials are not initialzed. XMPP Connections impossible"
186             self.error(msg)
187             raise
188
189         super(OMFApplication, self).start()
190
191     @failtrap
192     def stop(self):
193         """ Stop the RM. It means : Send Xmpp Message Using OMF protocol to 
194         kill the application. 
195         State is set to STOPPED after the message is sent.
196
197         """
198         try:
199             self._omf_api.exit(self.node.get('hostname'),self.get('appid'))
200         except AttributeError:
201             msg = "Credentials were not initialzed. XMPP Connections impossible"
202             self.error(msg)
203             raise
204
205         super(OMFApplication, self).stop()
206         self.set_finished()
207
208     def release(self):
209         """ Clean the RM at the end of the experiment and release the API.
210
211         """
212         try:
213             if self._omf_api :
214                 OMFAPIFactory.release_api(self.get('xmppSlice'), 
215                     self.get('xmppHost'), self.get('xmppPort'), 
216                     self.get('xmppPassword'), exp_id = self.exp_id)
217         except:
218             import traceback
219             err = traceback.format_exc()
220             self.error(err)
221
222         super(OMFApplication, self).release()
223