applied the except and raise fixers to the master branch to close the gap with py3
[nepi.git] / src / nepi / resources / linux / ccn / ccnd.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 version 2 as
7 #    published by the Free Software Foundation;
8 #
9 #    This program is distributed in the hope that it will be useful,
10 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #    GNU General Public License for more details.
13 #
14 #    You should have received a copy of the GNU General Public License
15 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
18
19 from nepi.execution.attribute import Attribute, Flags, Types
20 from nepi.execution.trace import Trace, TraceAttr
21 from nepi.execution.resource import ResourceManager, clsinit_copy, \
22         ResourceState
23 from nepi.resources.linux.application import LinuxApplication
24 from nepi.resources.linux.node import OSType
25 from nepi.util.timefuncs import tnow, tdiffsec
26
27 import os
28
29 # TODO: use ccndlogging to dynamically change the logging level
30
31
32 @clsinit_copy
33 class LinuxCCND(LinuxApplication):
34     _rtype = "linux::CCND"
35
36     @classmethod
37     def _register_attributes(cls):
38         debug = Attribute("debug", "Sets the CCND_DEBUG environmental variable. "
39             " Allowed values are : \n"
40             "  0 - no messages \n"
41             "  1 - basic messages (any non-zero value gets these) \n"
42             "  2 - interest messages \n"
43             "  4 - content messages \n"
44             "  8 - matching details \n"
45             "  16 - interest details \n"
46             "  32 - gory interest details \n"
47             "  64 - log occasional human-readable timestamps \n"
48             "  128 - face registration debugging \n"
49             "  -1 - max logging \n"
50             "  Or apply bitwise OR to these values to get combinations of them",
51             type = Types.Integer,
52             flags = Flags.Design)
53
54         port = Attribute("port", "Sets the CCN_LOCAL_PORT environmental variable. "
55             "Defaults to 9695 ", 
56             flags = Flags.Design)
57  
58         sockname = Attribute("sockname",
59             "Sets the CCN_LOCAL_SCOKNAME environmental variable. "
60             "Defaults to /tmp/.ccnd.sock", 
61             flags = Flags.Design)
62
63         capacity = Attribute("capacity",
64             "Sets the CCND_CAP environmental variable. "
65             "Capacity limit in terms of ContentObjects",
66             flags = Flags.Design)
67
68         mtu = Attribute("mtu", "Sets the CCND_MTU environmental variable. ",
69             flags = Flags.Design)
70   
71         data_pause = Attribute("dataPauseMicrosec",
72             "Sets the CCND_DATA_PAUSE_MICROSEC environmental variable. ",
73             flags = Flags.Design)
74
75         default_stale = Attribute("defaultTimeToStale",
76              "Sets the CCND_DEFAULT_TIME_TO_STALE environmental variable. ",
77             flags = Flags.Design)
78
79         max_stale = Attribute("maxTimeToStale",
80             "Sets the CCND_MAX_TIME_TO_STALE environmental variable. ",
81             flags = Flags.Design)
82
83         max_rte = Attribute("maxRteMicrosec",
84             "Sets the CCND_MAX_RTE_MICROSEC environmental variable. ",
85             flags = Flags.Design)
86
87         keystore = Attribute("keyStoreDirectory",
88             "Sets the CCND_KEYSTORE_DIRECTORY environmental variable. ",
89             flags = Flags.Design)
90
91         listen_on = Attribute("listenOn",
92             "Sets the CCND_LISTEN_ON environmental variable. ",
93             flags = Flags.Design)
94
95         autoreg = Attribute("autoreg",
96             "Sets the CCND_AUTOREG environmental variable. ",
97             flags = Flags.Design)
98
99         prefix = Attribute("prefix",
100             "Sets the CCND_PREFIX environmental variable. ",
101             flags = Flags.Design)
102
103         cls._register_attribute(debug)
104         cls._register_attribute(port)
105         cls._register_attribute(sockname)
106         cls._register_attribute(capacity)
107         cls._register_attribute(mtu)
108         cls._register_attribute(data_pause)
109         cls._register_attribute(default_stale)
110         cls._register_attribute(max_stale)
111         cls._register_attribute(max_rte)
112         cls._register_attribute(keystore)
113         cls._register_attribute(listen_on)
114         cls._register_attribute(autoreg)
115         cls._register_attribute(prefix)
116
117     @classmethod
118     def _register_traces(cls):
119         log = Trace("log", "CCND log output")
120         status = Trace("status", "ccndstatus output")
121
122         cls._register_trace(log)
123         cls._register_trace(status)
124
125     def __init__(self, ec, guid):
126         super(LinuxCCND, self).__init__(ec, guid)
127         self._home = "ccnd-%s" % self.guid
128         self._version = "ccnx"
129
130     @property
131     def version(self):
132         return self._version
133
134     @property
135     def path(self):
136         return "PATH=$PATH:${BIN}/%s/" % self.version 
137
138     def do_deploy(self):
139         if not self.node or self.node.state < ResourceState.READY:
140             self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
141             
142             # ccnd needs to wait until node is deployed and running
143             self.ec.schedule(self.reschedule_delay, self.deploy)
144         else:
145             if not self.get("command"):
146                 self.set("command", self._start_command)
147             
148             if not self.get("depends"):
149                 self.set("depends", self._dependencies)
150
151             if not self.get("sources"):
152                 self.set("sources", self._sources)
153
154             sources = self.get("sources")
155             source = sources.split(" ")[0]
156             basename = os.path.basename(source)
157             self._version = ( basename.strip().replace(".tar.gz", "")
158                     .replace(".tar","")
159                     .replace(".gz","")
160                     .replace(".zip","") )
161
162             if not self.get("build"):
163                 self.set("build", self._build)
164
165             if not self.get("install"):
166                 self.set("install", self._install)
167
168             if not self.get("env"):
169                 self.set("env", self._environment)
170
171             command = self.get("command")
172
173             self.info("Deploying command '%s' " % command)
174
175             self.do_discover()
176             self.do_provision()
177
178             self.set_ready()
179
180     def upload_start_command(self):
181         command = self.get("command")
182         env = self.get("env")
183
184         # We want to make sure the ccnd is running
185         # before the experiment starts.
186         # Run the command as a bash script in background,
187         # in the host ( but wait until the command has
188         # finished to continue )
189         env = self.replace_paths(env)
190         command = self.replace_paths(command)
191
192         shfile = os.path.join(self.app_home, "start.sh")
193         self.node.run_and_wait(command, self.run_home,
194                 shfile = shfile,
195                 overwrite = False,
196                 env = env)
197
198     def do_start(self):
199         if self.state == ResourceState.READY:
200             command = self.get("command")
201             self.info("Starting command '%s'" % command)
202
203             self.set_started()
204         else:
205             msg = " Failed to execute command '%s'" % command
206             self.error(msg, out, err)
207             raise RuntimeError(msg)
208
209     def do_stop(self):
210         command = self.get('command') or ''
211         
212         if self.state == ResourceState.STARTED:
213             self.info("Stopping command '%s'" % command)
214
215             command = "ccndstop"
216             env = self.get("env") 
217
218             # replace application specific paths in the command
219             command = self.replace_paths(command)
220             env = env and self.replace_paths(env)
221
222             # Upload the command to a file, and execute asynchronously
223             shfile = os.path.join(self.app_home, "stop.sh")
224             self.node.run_and_wait(command, self.run_home,
225                         shfile = shfile,
226                         overwrite = False,
227                         env = env,
228                         pidfile = "ccndstop_pidfile", 
229                         ecodefile = "ccndstop_exitcode", 
230                         stdout = "ccndstop_stdout", 
231                         stderr = "ccndstop_stderr")
232
233             self.set_stopped()
234     
235     @property
236     def state(self):
237         # First check if the ccnd has failed
238         state_check_delay = 0.5
239         if self._state == ResourceState.STARTED and \
240                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
241             (out, err), proc = self._ccndstatus()
242
243             retcode = proc.poll()
244
245             if retcode == 1 and err.find("No such file or directory") > -1:
246                 # ccnd is not running (socket not found)
247                 self.set_stopped()
248             elif retcode:
249                 # other errors ...
250                 msg = " Failed to execute command '%s'" % self.get("command")
251                 self.error(msg, out, err)
252                 self.fail()
253
254             self._last_state_check = tnow()
255
256         return self._state
257
258     def _ccndstatus(self):
259         env = self.get('env') or ""
260         environ = self.node.format_environment(env, inline = True)
261         command = environ + " ccndstatus"
262         command = self.replace_paths(command)
263     
264         return self.node.execute(command)
265
266     @property
267     def _start_command(self):
268         return "ccndstart"
269
270     @property
271     def _dependencies(self):
272         if self.node.use_rpm:
273             return ( " autoconf openssl-devel  expat-devel libpcap-devel "
274                 " ecryptfs-utils-devel libxml2-devel automake gawk " 
275                 " gcc gcc-c++ git pcre-devel make ")
276         elif self.node.use_deb:
277             return ( " autoconf libssl-dev libexpat-dev libpcap-dev "
278                 " libecryptfs0 libxml2-utils automake gawk gcc g++ "
279                 " git-core pkg-config libpcre3-dev make ")
280         return ""
281
282     @property
283     def _sources(self):
284         return "http://www.ccnx.org/releases/ccnx-0.8.2.tar.gz"
285
286     @property
287     def _build(self):
288         sources = self.get("sources").split(" ")[0]
289         sources = os.path.basename(sources)
290
291         return (
292             # Evaluate if ccnx binaries are already installed
293             " ( "
294                 " test -f ${BIN}/%(version)s/ccnd && "
295                 " echo 'binaries found, nothing to do' "
296             " ) || ( "
297             # If not, untar and build
298                 " ( "
299                     " mkdir -p ${SRC}/%(version)s && "
300                     " tar xf ${SRC}/%(sources)s --strip-components=1 -C ${SRC}/%(version)s "
301                  " ) && "
302                     "cd ${SRC}/%(version)s && "
303                     # Just execute and silence warnings...
304                     " ( ./configure && make ) "
305              " )") % ({ 'sources': sources,
306                         'version': self.version
307                  })
308
309     @property
310     def _install(self):
311         return (
312             # Evaluate if ccnx binaries are already installed
313             " ( "
314                 " test -f ${BIN}/%(version)s/ccnd && "
315                 " echo 'binaries found, nothing to do' "
316             " ) || ( "
317             # If not, install
318                 "  mkdir -p ${BIN}/%(version)s && "
319                 "  mv ${SRC}/%(version)s/bin/* ${BIN}/%(version)s/ "
320             " )"
321             ) % ({ 'version': self.version
322                  })
323
324     @property
325     def _environment(self):
326         envs = dict({
327             "debug": "CCND_DEBUG",
328             "port": "CCN_LOCAL_PORT",
329             "sockname" : "CCN_LOCAL_SOCKNAME",
330             "capacity" : "CCND_CAP",
331             "mtu" : "CCND_MTU",
332             "dataPauseMicrosec" : "CCND_DATA_PAUSE_MICROSEC",
333             "defaultTimeToStale" : "CCND_DEFAULT_TIME_TO_STALE",
334             "maxTimeToStale" : "CCND_MAX_TIME_TO_STALE",
335             "maxRteMicrosec" : "CCND_MAX_RTE_MICROSEC",
336             "keyStoreDirectory" : "CCND_KEYSTORE_DIRECTORY",
337             "listenOn" : "CCND_LISTEN_ON",
338             "autoreg" : "CCND_AUTOREG",
339             "prefix" : "CCND_PREFIX",
340             })
341
342         env = self.path 
343         env += " ".join(map(lambda k: "%s=%s" % (envs.get(k), str(self.get(k))) \
344             if self.get(k) else "", envs.keys()))
345         
346         return env            
347
348     def valid_connection(self, guid):
349         # TODO: Validate!
350         return True
351