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