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