Fixed nasty concurrency bug in EC
[nepi.git] / src / nepi / resources / linux / 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
26 from nepi.util.sshfuncs import ProcStatus
27 from nepi.util.timefuncs import strfnow, strfdiff
28 import os
29
30 @clsinit_copy
31 class LinuxCCND(LinuxApplication):
32     _rtype = "LinuxCCND"
33
34     @classmethod
35     def _register_attributes(cls):
36         debug = Attribute("debug", "Sets the CCND_DEBUG environmental variable. "
37             " Allowed values are : \n"
38             "  0 - no messages \n"
39             "  1 - basic messages (any non-zero value gets these) \n"
40             "  2 - interest messages \n"
41             "  4 - content messages \n"
42             "  8 - matching details \n"
43             "  16 - interest details \n"
44             "  32 - gory interest details \n"
45             "  64 - log occasional human-readable timestamps \n"
46             "  128 - face registration debugging \n"
47             "  -1 - max logging \n"
48             "  Or apply bitwise OR to these values to get combinations of them",
49             flags = Flags.ExecReadOnly)
50
51         port = Attribute("port", "Sets the CCN_LOCAL_PORT environmental variable. "
52             "Defaults to 9695 ", 
53             flags = Flags.ExecReadOnly)
54  
55         sockname = Attribute("sockname",
56             "Sets the CCN_LOCAL_SCOKNAME environmental variable. "
57             "Defaults to /tmp/.ccnd.sock", 
58             flags = Flags.ExecReadOnly)
59
60         capacity = Attribute("capacity",
61             "Sets the CCND_CAP environmental variable. "
62             "Capacity limit in terms of ContentObjects",
63             flags = Flags.ExecReadOnly)
64
65         mtu = Attribute("mtu", "Sets the CCND_MTU environmental variable. ",
66             flags = Flags.ExecReadOnly)
67   
68         data_pause = Attribute("dataPauseMicrosec",
69             "Sets the CCND_DATA_PAUSE_MICROSEC environmental variable. ",
70             flags = Flags.ExecReadOnly)
71
72         default_stale = Attribute("defaultTimeToStale",
73              "Sets the CCND_DEFAULT_TIME_TO_STALE environmental variable. ",
74             flags = Flags.ExecReadOnly)
75
76         max_stale = Attribute("maxTimeToStale",
77             "Sets the CCND_MAX_TIME_TO_STALE environmental variable. ",
78             flags = Flags.ExecReadOnly)
79
80         max_rte = Attribute("maxRteMicrosec",
81             "Sets the CCND_MAX_RTE_MICROSEC environmental variable. ",
82             flags = Flags.ExecReadOnly)
83
84         keystore = Attribute("keyStoreDirectory",
85             "Sets the CCND_KEYSTORE_DIRECTORY environmental variable. ",
86             flags = Flags.ExecReadOnly)
87
88         listen_on = Attribute("listenOn",
89             "Sets the CCND_LISTEN_ON environmental variable. ",
90             flags = Flags.ExecReadOnly)
91
92         autoreg = Attribute("autoreg",
93             "Sets the CCND_AUTOREG environmental variable. ",
94             flags = Flags.ExecReadOnly)
95
96         prefix = Attribute("prefix",
97             "Sets the CCND_PREFIX environmental variable. ",
98             flags = Flags.ExecReadOnly)
99
100         cls._register_attribute(debug)
101         cls._register_attribute(port)
102         cls._register_attribute(sockname)
103         cls._register_attribute(capacity)
104         cls._register_attribute(mtu)
105         cls._register_attribute(data_pause)
106         cls._register_attribute(default_stale)
107         cls._register_attribute(max_stale)
108         cls._register_attribute(max_rte)
109         cls._register_attribute(keystore)
110         cls._register_attribute(listen_on)
111         cls._register_attribute(autoreg)
112         cls._register_attribute(prefix)
113
114     @classmethod
115     def _register_traces(cls):
116         log = Trace("log", "CCND log output")
117         status = Trace("status", "ccndstatus output")
118
119         cls._register_trace(log)
120         cls._register_trace(status)
121
122     def __init__(self, ec, guid):
123         super(LinuxCCND, self).__init__(ec, guid)
124
125     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
126         self.info("Retrieving '%s' trace %s " % (name, attr))
127
128         path = os.path.join(self.app_home, name)
129         
130         command = "(test -f %s && echo 'success') || echo 'error'" % path
131         (out, err), proc = self.node.execute(command)
132
133         if (err and proc.poll()) or out.find("error") != -1:
134             msg = " Couldn't find trace %s " % name
135             self.error(msg, out, err)
136             return None
137     
138         if attr == TraceAttr.PATH:
139             return path
140
141         if attr == TraceAttr.ALL:
142             (out, err), proc = self.node.check_output(self.app_home, name)
143             
144             if err and proc.poll():
145                 msg = " Couldn't read trace %s " % name
146                 self.error(msg, out, err)
147                 return None
148
149             return out
150
151         if attr == TraceAttr.STREAM:
152             cmd = "dd if=%s bs=%d count=1 skip=%d" % (path, block, offset)
153         elif attr == TraceAttr.SIZE:
154             cmd = "stat -c%%s %s " % path
155
156         (out, err), proc = self.node.execute(cmd)
157
158         if err and proc.poll():
159             msg = " Couldn't find trace %s " % name
160             self.error(msg, out, err)
161             return None
162         
163         if attr == TraceAttr.SIZE:
164             out = int(out.strip())
165
166         return out
167             
168     def deploy(self):
169         if not self.get("command"):
170             self.set("command", self._default_command)
171         
172         if not self.get("depends"):
173             self.set("depends", self._default_dependencies)
174
175         if not self.get("sources"):
176             self.set("sources", self._default_sources)
177
178         if not self.get("build"):
179             self.set("build", self._default_build)
180
181         if not self.get("install"):
182             self.set("install", self._default_install)
183
184         if not self.get("env"):
185             self.set("env", self._default_environment)
186
187         super(LinuxCCND, self).deploy()
188
189     def start(self):
190         super(LinuxCCND, self).start()
191
192     def stop(self):
193         command = self.get('command') or ''
194         state = self.state
195         
196         if state == ResourceState.STARTED:
197             self.info("Stopping command '%s'" % command)
198
199             command = "ccndstop"
200             env = self.get("env") 
201
202             # replace application specific paths in the command
203             command = self.replace_paths(command)
204             env = env and self.replace_paths(env)
205
206             # Upload the command to a file, and execute asynchronously
207             self.node.run_and_wait(command, self.app_home,
208                         shfile = "ccndstop.sh",
209                         env = env,
210                         pidfile = "ccndstop_pidfile", 
211                         ecodefile = "ccndstop_exitcode", 
212                         stdout = "ccndstop_stdout", 
213                         stderr = "ccndstop_stderr")
214
215
216             super(LinuxCCND, self).stop()
217
218     @property
219     def state(self):
220         if self._state == ResourceState.STARTED:
221             # we executed the ccndstart command. This should have started
222             # a remote ccnd daemon. The way we can query wheather ccnd is
223             # still running is by executing the ccndstatus command.
224             state_check_delay = 0.5
225             if strfdiff(strfnow(), self._last_state_check) > state_check_delay:
226                 env = self.get('env') or ""
227                 environ = self.node.format_environment(env, inline = True)
228                 command = environ + "; ccndstatus"
229                 command = self.replace_paths(command)
230             
231                 (out, err), proc = self.node.execute(command)
232
233                 retcode = proc.poll()
234
235                 if retcode == 1 and err.find("No such file or directory") > -1:
236                     # ccnd is not running (socket not found)
237                     self._state = ResourceState.FINISHED
238                 elif retcode:
239                     # other error
240                     msg = " Failed to execute command '%s'" % command
241                     self.error(msg, out, err)
242                     self._state = ResourceState.FAILED
243
244                 self._last_state_check = strfnow()
245
246         return self._state
247
248     @property
249     def _default_command(self):
250         return "ccndstart"
251
252     @property
253     def _default_dependencies(self):
254         if self.node.os in [ OSType.FEDORA_12 , OSType.FEDORA_14 ]:
255             return ( " autoconf openssl-devel  expat-devel libpcap-devel "
256                 " ecryptfs-utils-devel libxml2-devel automake gawk " 
257                 " gcc gcc-c++ git pcre-devel make ")
258         elif self.node.os in [ OSType.UBUNTU , OSType.DEBIAN]:
259             return ( " autoconf libssl-dev libexpat-dev libpcap-dev "
260                 " libecryptfs0 libxml2-utils automake gawk gcc g++ "
261                 " git-core pkg-config libpcre3-dev make ")
262         return ""
263
264     @property
265     def _default_sources(self):
266         return "http://www.ccnx.org/releases/ccnx-0.7.1.tar.gz"
267
268     @property
269     def _default_build(self):
270         sources = self.get("sources").split(" ")[0]
271         sources = os.path.basename(sources)
272
273         return (
274             # Evaluate if ccnx binaries are already installed
275             " ( "
276                 " test -f ${EXP_HOME}/ccnx/bin/ccnd && "
277                 " echo 'sources found, nothing to do' "
278             " ) || ( "
279             # If not, untar and build
280                 " ( "
281                     " mkdir -p ${SOURCES}/ccnx && "
282                     " tar xf ${SOURCES}/%(sources)s --strip-components=1 -C ${SOURCES}/ccnx "
283                  " ) && "
284                     "cd ${SOURCES}/ccnx && "
285                     # Just execute and silence warnings...
286                     " ( ./configure && make ) "
287              " )") % ({ 'sources': sources })
288
289     @property
290     def _default_install(self):
291         return (
292             # Evaluate if ccnx binaries are already installed
293             " ( "
294                 " test -f ${EXP_HOME}/ccnx/bin/ccnd && "
295                 " echo 'sources found, nothing to do' "
296             " ) || ( "
297             # If not, install
298                 "  mkdir -p ${EXP_HOME}/ccnx/bin && "
299                 "  cp -r ${SOURCES}/ccnx ${EXP_HOME}"
300             " )"
301             )
302
303     @property
304     def _default_environment(self):
305         envs = dict({
306             "debug": "CCND_DEBUG",
307             "port": "CCN_LOCAL_PORT",
308             "sockname" : "CCN_LOCAL_SOCKNAME",
309             "capacity" : "CCND_CAP",
310             "mtu" : "CCND_MTU",
311             "dataPauseMicrosec" : "CCND_DATA_PAUSE_MICROSEC",
312             "defaultTimeToStale" : "CCND_DEFAULT_TIME_TO_STALE",
313             "maxTimeToStale" : "CCND_MAX_TIME_TO_STALE",
314             "maxRteMicrosec" : "CCND_MAX_RTE_MICROSEC",
315             "keyStoreDirectory" : "CCND_KEYSTORE_DIRECTORY",
316             "listenOn" : "CCND_LISTEN_ON",
317             "autoreg" : "CCND_AUTOREG",
318             "prefix" : "CCND_PREFIX",
319             })
320
321         env = "PATH=$PATH:${EXP_HOME}/ccnx/bin"
322         for key in envs.keys():
323             val = self.get(key)
324             if val:
325                 env += " %s=%s" % (key, val)
326         
327         return env            
328         
329     def valid_connection(self, guid):
330         # TODO: Validate!
331         return True
332