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