3e159030e0231d295a47f30e1107cfb0930cfcf3
[senf.git] / senf / Utils / Daemon / Daemon.hh
1 // $Id$
2 //
3 // Copyright (C) 2007
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 //
6 // The contents of this file are subject to the Fraunhofer FOKUS Public License
7 // Version 1.0 (the "License"); you may not use this file except in compliance
8 // with the License. You may obtain a copy of the License at 
9 // http://senf.berlios.de/license.html
10 //
11 // The Fraunhofer FOKUS Public License Version 1.0 is based on, 
12 // but modifies the Mozilla Public License Version 1.1.
13 // See the full license text for the amendments.
14 //
15 // Software distributed under the License is distributed on an "AS IS" basis, 
16 // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
17 // for the specific language governing rights and limitations under the License.
18 //
19 // The Original Code is Fraunhofer FOKUS code.
20 //
21 // The Initial Developer of the Original Code is Fraunhofer-Gesellschaft e.V. 
22 // (registered association), Hansastraße 27 c, 80686 Munich, Germany.
23 // All Rights Reserved.
24 //
25 // Contributor(s):
26 //   Stefan Bund <g0dil@berlios.de>
27
28 /** \file
29     \brief Daemon public header */
30
31 #ifndef HH_SENF_Utils_Daemon_Daemon_
32 #define HH_SENF_Utils_Daemon_Daemon_ 1
33
34 // Custom includes
35 #include <senf/Utils/Logger/SenfLog.hh>
36
37 //#include "Daemon.mpp"
38 //-/////////////////////////////////////////////////////////////////////////////////////////////////
39
40 namespace senf {
41
42     /** \brief %Daemon process
43
44         The %Daemon class provides simple management for daemon processes. Specifically, it
45         implements
46         \li <i>Safe startup.</i> If the startup fails, the foreground process which launches the
47             daemon will terminate with an appropriate error exit code.
48         \li <i>Straight forward application initialization.</i> The daemon process is forked before
49             even initializing the application. The initialization procedure doesn't need to cater
50             for a later fork().
51         \li <i>Automatic pid file management.</i> The daemon will not be started, if a valid pid
52             file is found. Stale pid files are automatically removed.
53         \li <i>Console %log management.</i> It is possible, to redirect standard output and error to
54             one or two %log files. Messages pertaining to application initialization will be written
55             to both the %console and the %log file whereas later messages will be directed to the log
56             file only.
57         \li <i>Optional foreground execution.</i> The daemon may be started in the foreground for
58             debugging purposes. In this case, the %console %log file(s) is/are automatically
59             suppressed.
60
61         Starting the daemon process proceeds along the following steps:
62         \li The daemon is started by calling the daemon class instances start() member. This
63             normally happens from the \c main() function generated by \ref SENF_DAEMON_MAIN().
64         \li configure() is called. This (virtual) member configures the daemon manager by calling
65             the Daemon class parameter members.
66         \li The %log files are opened, \c fork() is called and the pid file is checked and
67             created. The parent (foreground) process keeps running overseeing the daemon process.
68         \li main() is called. This virtual member may optionally be overridden in the derived
69             class. Here we assume, main() is not overridden so the default implementation is used.
70         \li main() calls init().
71         \li after init() returns, main() calls detach().
72         \li detach() signals successful startup to the parent process. The parent process terminates
73             leaving the daemon process running in the background.
74         \li main() calls run()
75         \li If run() ever returns, the daemon process terminates.
76         \li Whenever the process terminates normally (not necessarily successfully), the pid file is
77             automatically removed.
78
79         The parameter members are used from configure() to configure the daemon manager. See below
80         for details. The \e default configure() implementation will scan the command line arguments
81         to check for the following parameters:
82
83         <table class="senf">
84
85         <tr><td><tt>--no-daemon</tt></td><td>Run in foreground</td></tr>
86
87         <tr><td><tt>--console-log=</tt><i>stdout</i>[<tt>,</tt><i>stderr</i>]</td><td>Set the
88         %console %log file(s). If only \a stdout is specified (with no comma), the same %log file
89         configuration will be applied to the standard output and error stream. Otherwise each stream
90         is assigned it's own %log file. If either %log file name is empty, the command will not change
91         the %log file of that stream, the default %log file will be used. If the %log file name is set
92         to 'none', the %log file will be disabled.</td></tr>
93
94         <tr><td><tt>--pid-file=</tt><i>pidfile</i></td><td>Set pid file path</td></tr>
95
96         </table>
97
98         The default configure() implementation will use whatever parameters have been set beforehand
99         as default values. These default values should be set in a derived class configure()
100         implementation. After setting the default values, the configure() implementation may choose
101         to call this default configure() implementation to scan for command line parameters.  The
102         default configure() implementation does \e not completely parse the command line
103         arguments. It just checks, if any of above arguments are present and processes them. Other
104         arguments are completely ignored. The command line parameters should be completely processed
105         within init().
106
107       */
108     class Daemon : boost::noncopyable
109     {
110     public:
111         SENF_LOG_CLASS_AREA();
112
113         //-/////////////////////////////////////////////////////////////////////////
114         // Types
115
116         /// Select standard stream to redirect
117         enum StdStream {
118             StdOut  /** Standard output stream */
119         ,   StdErr  /** Standard error stream */
120         ,   Both    /** Both, standard output and error stream */
121         };
122
123         //-/////////////////////////////////////////////////////////////////////////
124         ///\name Structors and default members
125         //\{
126
127         virtual ~Daemon();
128
129         //\}
130         ///\name Parameters
131         //\{
132
133         void daemonize(bool);           ///< Configure whether to run in fore- or background
134         bool daemon();                  ///< \c true, if running as daemon
135
136         void consoleLog(std::string const &, StdStream which = Both);
137                                         ///< Configure %console %log file
138                                         /**< May be called multiple times to set the %log file
139                                              for stdout and stderr separately. Any standard stream
140                                              not assigned to a %log file will be redirected to
141                                              <tt>/dev/null</tt>.
142
143                                              When running in the foreground, the %log files will be
144                                              ignored. */
145
146         void pidFile(std::string const &); ///< Configure pid file
147                                         /**< If a pid file is configured it will be checked on
148                                              daemon startup. If another running instance of the
149                                              daemon is detected, starting the daemon will fail. */
150
151         //\}
152         ///\name Auxiliary helpers
153         //\{
154
155         void detach();                  ///< Detach into background now
156                                         /**< This is \e not the same as forking. The process will
157                                              already have forked into the background but until
158                                              detach() is called (either automatically after init()
159                                              returns or manually), the front end (foreground)
160                                              process will wait for the background process to ensure
161                                              successful startup. */
162
163         int argc();                     ///< Access command line parameter count
164         char const ** argv();           ///< Access command line parameters
165         void removeDaemonArgs();        ///< Remove the daemon arguments from argc()/argv()
166
167         static void exit(unsigned code=0); ///< Terminate daemon with failure
168
169         void logReopen();               ///< Reopen the %log files
170                                         /**< This is used when rotating the logs. By default,
171                                              SIGHUP calls logReopen. */
172
173         //\}
174
175         int start(int argc, char const ** argv); ///< Called from main() to launch daemon.
176                                         /**< Normally not called directly but from the
177                                              \ref SENF_DAEMON_MAIN macro. */
178
179         static Daemon & instance();     ///< Return the Daemon instance
180
181     protected:
182         Daemon();
183
184         virtual void configure();       ///< Called before forking to configure the daemon class
185                                         /**< This default implementation will parser some command
186                                              line parameters. See the class documentation above. */
187
188 #   ifdef DOXYGEN
189     protected:
190 #   else
191     private:
192 #   endif
193
194         virtual void main();            ///< Called after forking to execute the main application
195                                         /**< The default implementation will call init(), detach()
196                                              and then run(). It is preferred to override init() and
197                                              run() if possible. */
198         virtual void init();            ///< Called to initialize the main application
199                                         /**< While init() is running, the application still is
200                                              connected to the controlling terminal. Error messages
201                                              will be shown to the user.
202
203                                              This member is only called, if the default main()
204                                              implementation is not overridden. */
205         virtual void run();             ///< Called to execute main application
206                                         /**< Called after detaching from the controlling
207                                              terminal.
208
209                                              This member is only called, if the default main()
210                                              implementation is not overridden. */
211     private:
212         void openLog();
213         void fork();
214         bool pidfileCreate();
215         void installSighandlers();
216
217         int argc_;
218         char const ** argv_;
219
220         bool daemonize_;
221         std::string stdoutLog_;
222         std::string stderrLog_;
223         int stdout_;
224         int stderr_;
225         std::string pidfile_;
226         bool pidfileCreated_;
227
228         bool detached_;
229
230         static Daemon * instance_;
231     };
232
233     /** \brief Provide \c main() function
234
235         This macro will provide a \c main() function to launch the daemon process defined in \a
236         klass. \a klass must be a class derived from senf::Daemon.
237
238         \ingroup process
239      */
240 #   define SENF_DAEMON_MAIN(klass)                                                                \
241         int main(int argc, char const ** argv)                                                    \
242         {                                                                                         \
243             klass instance;                                                                       \
244             return instance.start(argc, argv);                                                    \
245         }
246
247 }
248
249 //-/////////////////////////////////////////////////////////////////////////////////////////////////
250 #include "Daemon.cci"
251 //#include "Daemon.ct"
252 //#include "Daemon.cti"
253 #endif
254
255 \f
256 // Local Variables:
257 // mode: c++
258 // fill-column: 100
259 // comment-column: 40
260 // c-file-style: "senf"
261 // indent-tabs-mode: nil
262 // ispell-local-dictionary: "american"
263 // compile-command: "scons -u test"
264 // End: