First CCN RMs working example for Linux
[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 strfnow, strfdiff
26
27 import os
28
29 @clsinit_copy
30 class LinuxCCND(LinuxApplication):
31     _rtype = "LinuxCCND"
32
33     @classmethod
34     def _register_attributes(cls):
35         debug = Attribute("debug", "Sets the CCND_DEBUG environmental variable. "
36             " Allowed values are : \n"
37             "  0 - no messages \n"
38             "  1 - basic messages (any non-zero value gets these) \n"
39             "  2 - interest messages \n"
40             "  4 - content messages \n"
41             "  8 - matching details \n"
42             "  16 - interest details \n"
43             "  32 - gory interest details \n"
44             "  64 - log occasional human-readable timestamps \n"
45             "  128 - face registration debugging \n"
46             "  -1 - max logging \n"
47             "  Or apply bitwise OR to these values to get combinations of them",
48             type = Types.Integer,
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         self._home = "ccnd-%s" % self.guid
125
126         # Marks whether daemon is running
127         self._running = False
128
129     def deploy(self):
130         if not self.get("command"):
131             self.set("command", self._default_command)
132         
133         if not self.get("depends"):
134             self.set("depends", self._default_dependencies)
135
136         if not self.get("sources"):
137             self.set("sources", self._default_sources)
138
139         if not self.get("build"):
140             self.set("build", self._default_build)
141
142         if not self.get("install"):
143             self.set("install", self._default_install)
144
145         if not self.get("env"):
146             self.set("env", self._default_environment)
147
148         super(LinuxCCND, self).deploy()
149
150         # As soon as the ccnd sources are deployed, we launch the
151         # daemon ( we don't want to lose time launching the ccn 
152         # daemon later on )
153         if self._state == ResourceState.READY:
154             self._start_in_background()
155             self._running = True
156
157     def start(self):
158         # CCND should already be started by now.
159         # Nothing to do but to set the state to STARTED
160         if self._running:
161             self._start_time = strfnow()
162             self._state = ResourceState.STARTED
163         else:
164             msg = " Failed to execute command '%s'" % command
165             self.error(msg, out, err)
166             self._state = ResourceState.FAILED
167             raise RuntimeError, msg
168
169     def stop(self):
170         command = self.get('command') or ''
171         state = self.state
172         
173         if state == ResourceState.STARTED:
174             self.info("Stopping command '%s'" % command)
175
176             command = "ccndstop"
177             env = self.get("env") 
178
179             # replace application specific paths in the command
180             command = self.replace_paths(command)
181             env = env and self.replace_paths(env)
182
183             # Upload the command to a file, and execute asynchronously
184             self.node.run_and_wait(command, self.app_home,
185                         shfile = "ccndstop.sh",
186                         env = env,
187                         pidfile = "ccndstop_pidfile", 
188                         ecodefile = "ccndstop_exitcode", 
189                         stdout = "ccndstop_stdout", 
190                         stderr = "ccndstop_stderr")
191
192
193             super(LinuxCCND, self).stop()
194
195     @property
196     def state(self):
197         # First check if the ccnd has failed
198         state_check_delay = 0.5
199         if self._running and strfdiff(strfnow(), self._last_state_check) > state_check_delay:
200             (out, err), proc = self._ccndstatus
201
202             retcode = proc.poll()
203
204             if retcode == 1 and err.find("No such file or directory") > -1:
205                 # ccnd is not running (socket not found)
206                 self._running = False
207                 self._state = ResourceState.FINISHED
208             elif retcode:
209                 # other errors ...
210                 self._running = False
211                 msg = " Failed to execute command '%s'" % self.get("command")
212                 self.error(msg, out, err)
213                 self._state = ResourceState.FAILED
214
215             self._last_state_check = strfnow()
216
217         if self._state == ResourceState.READY:
218             # CCND is really deployed only when ccn daemon is running 
219             if not self._running:
220                 return ResourceState.PROVISIONED
221
222         return self._state
223
224     @property
225     def _ccndstatus(self):
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         return self.node.execute(command)
232
233     @property
234     def _default_command(self):
235         return "ccndstart"
236
237     @property
238     def _default_dependencies(self):
239         if self.node.os in [ OSType.FEDORA_12 , OSType.FEDORA_14 ]:
240             return ( " autoconf openssl-devel  expat-devel libpcap-devel "
241                 " ecryptfs-utils-devel libxml2-devel automake gawk " 
242                 " gcc gcc-c++ git pcre-devel make ")
243         elif self.node.os in [ OSType.UBUNTU , OSType.DEBIAN]:
244             return ( " autoconf libssl-dev libexpat-dev libpcap-dev "
245                 " libecryptfs0 libxml2-utils automake gawk gcc g++ "
246                 " git-core pkg-config libpcre3-dev make ")
247         return ""
248
249     @property
250     def _default_sources(self):
251         return "http://www.ccnx.org/releases/ccnx-0.7.2.tar.gz"
252
253     @property
254     def _default_build(self):
255         sources = self.get("sources").split(" ")[0]
256         sources = os.path.basename(sources)
257
258         return (
259             # Evaluate if ccnx binaries are already installed
260             " ( "
261                 " test -f ${EXP_HOME}/ccnx/bin/ccnd && "
262                 " echo 'sources found, nothing to do' "
263             " ) || ( "
264             # If not, untar and build
265                 " ( "
266                     " mkdir -p ${SOURCES}/ccnx && "
267                     " tar xf ${SOURCES}/%(sources)s --strip-components=1 -C ${SOURCES}/ccnx "
268                  " ) && "
269                     "cd ${SOURCES}/ccnx && "
270                     # Just execute and silence warnings...
271                     " ( ./configure && make ) "
272              " )") % ({ 'sources': sources })
273
274     @property
275     def _default_install(self):
276         return (
277             # Evaluate if ccnx binaries are already installed
278             " ( "
279                 " test -f ${EXP_HOME}/ccnx/bin/ccnd && "
280                 " echo 'sources found, nothing to do' "
281             " ) || ( "
282             # If not, install
283                 "  mkdir -p ${EXP_HOME}/ccnx/bin && "
284                 "  cp -r ${SOURCES}/ccnx ${EXP_HOME}"
285             " )"
286             )
287
288     @property
289     def _default_environment(self):
290         envs = dict({
291             "debug": "CCND_DEBUG",
292             "port": "CCN_LOCAL_PORT",
293             "sockname" : "CCN_LOCAL_SOCKNAME",
294             "capacity" : "CCND_CAP",
295             "mtu" : "CCND_MTU",
296             "dataPauseMicrosec" : "CCND_DATA_PAUSE_MICROSEC",
297             "defaultTimeToStale" : "CCND_DEFAULT_TIME_TO_STALE",
298             "maxTimeToStale" : "CCND_MAX_TIME_TO_STALE",
299             "maxRteMicrosec" : "CCND_MAX_RTE_MICROSEC",
300             "keyStoreDirectory" : "CCND_KEYSTORE_DIRECTORY",
301             "listenOn" : "CCND_LISTEN_ON",
302             "autoreg" : "CCND_AUTOREG",
303             "prefix" : "CCND_PREFIX",
304             })
305
306         env = "PATH=$PATH:${EXP_HOME}/ccnx/bin "
307         env += " ".join(map(lambda k: "%s=%s" % (envs.get(k), str(self.get(k))) \
308             if self.get(k) else "", envs.keys()))
309         
310         return env            
311         
312     def valid_connection(self, guid):
313         # TODO: Validate!
314         return True
315