Utils/Daemon: Documentation
[senf.git] / Utils / Daemon / Daemon.cc
1 // $Id$
2 //
3 // Copyright (C) 2007 
4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer NETwork research (NET)
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 non-inline non-template implementation */
25
26 #include "Daemon.hh"
27 #include "Daemon.ih"
28
29 // Custom includes
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #include <signal.h>
37 #include <sstream>
38 #include <algorithm>
39 #include <boost/algorithm/string/predicate.hpp>
40 #include <boost/algorithm/string/trim.hpp>
41 #include "../Exception.hh"
42 #include "../membind.hh"
43
44 //#include "Daemon.mpp"
45 #define prefix_
46 ///////////////////////////////cc.p////////////////////////////////////////
47
48 #define LIBC_CALL(fn, args) if (fn args < 0) throwErrno(#fn "()")
49 #define LIBC_CALL_RV(var, fn, args) int var (fn args); if (var < 0) throwErrno(#fn "()")
50
51 ///////////////////////////////////////////////////////////////////////////
52 // senf::Daemon
53
54 prefix_ senf::Daemon::~Daemon()
55 {
56     if (! pidfile_.empty())
57         LIBC_CALL( ::unlink, (pidfile_.c_str()) );
58 }
59
60 prefix_ void senf::Daemon::daemonize(bool v)
61 {
62     daemonize_ = v;
63 }
64
65 prefix_ bool senf::Daemon::daemon()
66 {
67     return daemonize_;
68 }
69
70 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
71 {
72     switch (which) {
73     case StdOut : stdoutLog_ = path; break;
74     case StdErr : stderrLog_ = path; break;
75     case Both : stdoutLog_ = path; stderrLog_ = path; break;
76     }
77 }
78
79
80 prefix_ void senf::Daemon::openLog()
81 {
82     int fd (-1);
83     if (! stdoutLog_.empty()) {
84         fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
85         if (fd < 0)
86             throwErrno("::open()");
87         stdout_ = fd;
88     }
89     if (stderrLog_ == stdoutLog_)
90         stderr_ = fd;
91     else if (! stderrLog_.empty()) {
92         fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
93         if (fd < 0)
94             throwErrno("::open()");
95         stderr_ = fd;
96     }
97 }
98
99 prefix_ void senf::Daemon::pidFile(std::string const & f)
100 {
101     pidfile_ = f;
102 }
103
104 namespace {
105     bool signaled (false);
106     void waitusr(int) {
107         signaled = true;
108     }
109 }
110
111 prefix_ void senf::Daemon::detach()
112 {
113     if (daemonize_ && ! detached_) {
114         // Wow .. ouch .. 
115         // To ensure all data is written to the console log file in the correct order, we suspend
116         // execution here until the parent process tells us to continue via SIGUSR1: We block
117         // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
118         // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
119         // SIGUSR1 and reinstall the old signal mask and action.
120         ::sigset_t oldsig;
121         ::sigset_t usrsig;
122         ::sigemptyset(&usrsig);
123         LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
124         LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
125         struct ::sigaction oldact;
126         struct ::sigaction usract;
127         ::memset(&usract, 0, sizeof(usract));
128         usract.sa_handler = &waitusr;
129         LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
130         ::sigset_t waitsig (oldsig);
131         LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
132
133         LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
134         LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
135         LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
136         LIBC_CALL( ::close, (nul) );
137
138         signaled = false;
139         while (! signaled) {
140             ::sigsuspend(&waitsig);
141             if (errno != EINTR)
142                 throwErrno("::sigsuspend()");
143         }
144
145         LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
146         LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
147
148         detached_ = true;
149     }
150 }
151
152 namespace {
153     /* Purposely *not* derived from std::exception */
154     struct  DaemonFailureException {
155         DaemonFailureException(unsigned c) : code(c) {}
156         unsigned code;
157     };
158 }
159
160 prefix_ void senf::Daemon::fail(unsigned code)
161 {
162     throw DaemonFailureException(code);
163 }
164
165 prefix_ int senf::Daemon::start(int argc, char const ** argv)
166 {
167     argc_ = argc;
168     argv_ = argv;
169
170     try {
171         configure();
172
173         if (daemonize_) {
174             openLog();
175             fork();
176         }
177         if (! pidfile_.empty() && ! pidfileCreate()) {
178             std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?" 
179                       << std::endl;
180             return 1;
181         }
182
183         main();
184     }
185     catch (DaemonFailureException & e) {
186         return e.code > 0 ? e.code : 1;
187     }
188
189 #ifdef NDEBUG
190
191     catch (std::exception & e) {
192         std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
193         return 1;
194     }
195     catch (...) {
196         std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
197         return 1;
198     }
199
200 #   endif
201
202     return 0;
203 }
204
205 ////////////////////////////////////////
206 // protected members
207
208 prefix_ senf::Daemon::Daemon()
209     : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
210       detached_(false)
211 {}
212
213 ////////////////////////////////////////
214 // private members
215
216 prefix_ void senf::Daemon::configure()
217 {
218     for (int i (1); i<argc_; ++i) {
219         if (argv_[i] == std::string("--no-daemon"))
220             daemonize(false);
221         else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
222             std::string arg (std::string(argv_[i]), 14u);
223             std::string::size_type komma (arg.find(','));
224             if (komma == std::string::npos) {
225                 boost::trim(arg);
226                 consoleLog(arg);
227             } else {
228                 std::string arg1 (arg,0,komma);
229                 std::string arg2 (arg,komma+1);
230                 boost::trim(arg1);
231                 boost::trim(arg2);
232                 if (arg1 == std::string("none")) consoleLog("",StdOut);
233                 else if (! arg1.empty() )        consoleLog(arg1, StdOut);
234                 if (arg2 == std::string("none")) consoleLog("",StdErr);
235                 else if (! arg2.empty() )        consoleLog(arg2, StdErr);
236             }
237         }
238         else if (boost::starts_with(argv_[i], std::string("--pid-file="))) 
239             pidFile(std::string(std::string(argv_[i]), 11u));
240     }
241 }
242
243 prefix_ void senf::Daemon::main()
244 {
245     init();
246     detach();
247     run();
248 }
249
250 prefix_ void senf::Daemon::init()
251 {}
252
253 prefix_ void senf::Daemon::run()
254 {}
255
256 prefix_ void senf::Daemon::fork()
257 {
258     int coutpipe[2];
259     int cerrpipe[2];
260
261     LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
262     LIBC_CALL( ::dup2, (nul, 0) );
263     LIBC_CALL( ::close, (nul) );
264     LIBC_CALL( ::pipe, (coutpipe) );
265     LIBC_CALL( ::pipe, (cerrpipe) );
266
267     // We need to block the SIGCHLD signal here so we don't miss it, if the child
268     // dies immediately
269     ::sigset_t oldsig;
270     ::sigset_t cldsig;
271     ::sigemptyset(&cldsig);
272     LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
273     LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
274     
275     LIBC_CALL_RV( pid, ::fork, () );
276
277     if (pid == 0) {
278         // Daemon process
279
280         LIBC_CALL( ::dup2, (coutpipe[1],1) );
281         LIBC_CALL( ::dup2, (cerrpipe[1],2) );
282         LIBC_CALL( ::close, (coutpipe[0]) );
283         LIBC_CALL( ::close, (coutpipe[1]) );
284         LIBC_CALL( ::close, (cerrpipe[0]) );
285         LIBC_CALL( ::close, (cerrpipe[1]) );
286         LIBC_CALL( ::setsid, () );
287         LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
288         return;
289     }
290
291     // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
292     pidfile_ = "";
293     
294     LIBC_CALL( ::close, (coutpipe[1]) );
295     LIBC_CALL( ::close, (cerrpipe[1]) );
296
297     detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
298     watcher.run();
299
300     ::_exit(0);
301 }
302
303 prefix_ bool senf::Daemon::pidfileCreate()
304 {
305     // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
306     // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
307     // was some race condition, probably over NFS.
308
309     std::string tempname;
310
311     {
312         char hostname[HOST_NAME_MAX+1];
313         LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
314         hostname[HOST_NAME_MAX] = 0;
315         std::stringstream tempname_s;
316         tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
317         tempname = tempname_s.str();
318     }
319
320     while (1) {
321         {
322             std::ofstream pidf (tempname.c_str());
323             pidf << ::getpid() << std::endl;
324         }
325
326         if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
327             if (errno != EEXIST) 
328                 throwErrno("::link()");
329         }
330         else {
331             struct ::stat s;
332             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
333             LIBC_CALL( ::unlink, (tempname.c_str()) );
334             return s.st_nlink == 2;
335         }
336
337         // pidfile exists. Check, whether the pid in the pidfile still exists.
338         {
339             int old_pid (-1);
340             std::ifstream pidf (pidfile_.c_str());
341             if ( ! (pidf >> old_pid)
342                  || old_pid < 0 
343                  || ::kill(old_pid, 0) >= 0 
344                  || errno == EPERM )
345                 return false;
346         }
347
348         // If we reach this point, the pid file exists but the process mentioned within the
349         // pid file does *not* exists. We assume, the pid file to be stale.
350
351         // I hope, the following procedure is without race condition: We remove our generated
352         // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
353         // the hard-link count of this file is 2. If it is not, we terminate, since someone else
354         // must have already created his hardlink. We then truncate the file and write our pid.
355
356         LIBC_CALL( ::unlink, (tempname.c_str() ));
357         if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
358             if (errno != ENOENT) throwErrno("::link()");
359             // Hmm ... the pidfile mysteriously disappeared ... try again.
360             continue;
361         }
362
363         {
364             struct ::stat s;
365             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
366             if (s.st_nlink != 2) {
367                 LIBC_CALL( ::unlink, (tempname.c_str()) );
368                 return false;
369             }
370         }
371         
372         {
373             std::ofstream pidf (tempname.c_str());
374             pidf << ::getpid() << std::endl;
375         }
376
377         LIBC_CALL( ::unlink, (tempname.c_str()) );
378         break;
379     }
380     return true;
381 }
382
383 ///////////////////////////////////////////////////////////////////////////
384 // senf::detail::DaemonWatcher
385
386 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
387                                                    int stdout, int stderr)
388     : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
389       stderr_(stderr), sigChld_(false),
390       coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)), 
391       cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2)) 
392 {
393     coutForwarder_.addTarget(1);
394     if (stdout_ >= 0)
395         coutForwarder_.addTarget(stdout_);
396     cerrForwarder_.addTarget(2);
397     if (stderr_ >= 0)
398         cerrForwarder_.addTarget(stderr_);
399 }
400
401 prefix_ void senf::detail::DaemonWatcher::run()
402 {
403     Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
404     Scheduler::instance().process();
405 }
406
407 ////////////////////////////////////////
408 // private members
409
410 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
411 {
412     switch (id) {
413     case 1 : coutpipe_ = -1; break;
414     case 2 : cerrpipe_ = -1; break;
415     }
416
417     if (coutpipe_ == -1 && cerrpipe_ == -1) {
418         if (sigChld_)
419             childDied(); // does not return
420         if (::kill(childPid_, SIGUSR1) < 0)
421             if (errno != ESRCH) throwErrno("::kill()");
422         Scheduler::instance().timeout(
423             Scheduler::instance().eventTime() + ClockService::seconds(1),
424             senf::membind(&DaemonWatcher::childOk, this));
425     }
426 }
427
428 prefix_ void senf::detail::DaemonWatcher::sigChld()
429 {
430     sigChld_ = true;
431     if (coutpipe_ == -1 && cerrpipe_ == -1)
432         childDied(); // does not return
433 }
434
435 prefix_ void senf::detail::DaemonWatcher::childDied()
436 {
437     int status (0);
438     if (::waitpid(childPid_,&status,0) < 0) throwErrno("::waitpid()");
439     if (WIFSIGNALED(status)) {
440         ::signal(WTERMSIG(status),SIG_DFL);
441         ::kill(::getpid(), WTERMSIG(status));
442         // should not be reached
443         ::_exit(1);
444     }
445     if (WEXITSTATUS(status) == 0)
446         ::_exit(1);
447     ::_exit(WEXITSTATUS(status));
448 }
449
450 prefix_ void senf::detail::DaemonWatcher::childOk()
451 {
452     Scheduler::instance().terminate();
453 }
454
455 ///////////////////////////////////////////////////////////////////////////
456 // senf::detail::DaemonWatcher::Forwarder
457
458 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
459     : src_(src), cb_(cb)
460 {
461     Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
462                               Scheduler::EV_READ);
463 }
464
465 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
466 {
467     if (src_ != -1)
468         Scheduler::instance().remove(src_);
469     
470     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
471         if (i->offset >= buffer_.size())
472             Scheduler::instance().remove(i->fd);
473 }
474
475 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
476 {
477     Target target = { fd, 0 };
478     targets_.push_back(target);
479 }
480
481 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
482 {
483     char buf[1024];
484     int n (0);
485
486     while (1) {
487         n = ::read(src_,buf,1024);
488         if (n<0) {
489             if (errno != EINTR) throwErrno("::read()");
490         } else 
491             break;
492     }
493
494     if (n == 0) {
495         // Hangup
496         Scheduler::instance().remove(src_);
497         if (buffer_.empty())
498             cb_(); 
499         src_ = -1;
500         return;
501     }
502
503     if (targets_.empty())
504         return;
505
506     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
507         if (i->offset >= buffer_.size())
508             Scheduler::instance().add( i->fd, 
509                                        boost::bind(&Forwarder::writeData, this, _1, i),
510                                        Scheduler::EV_WRITE );
511
512     buffer_.insert(buffer_.end(), buf, buf+n);
513 }
514
515 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
516                                                                Targets::iterator target)
517 {    
518     if (event != Scheduler::EV_WRITE) {
519         // Broken pipe while writing data ? Not much, we can do here, we just drop the data
520         Scheduler::instance().remove(target->fd);
521         targets_.erase(target);
522         if (targets_.empty() && src_ == -1)
523             cb_();
524         return;
525     }
526
527     char buf[1024];
528     int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
529     std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
530
531     int w (::write(target->fd, buf, n));
532     if (w < 0) {
533         if (errno != EINTR) throwErrno("::write()");
534         return;
535     }
536     target->offset += w;
537
538     n = std::min_element(
539         targets_.begin(), targets_.end(),
540         boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
541
542     buffer_.erase(buffer_.begin(), buffer_.begin()+n);
543
544     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
545         i->offset -= n;
546
547     if (target->offset >= buffer_.size())
548         Scheduler::instance().remove(target->fd);
549     if (src_ == -1 && (buffer_.empty() || targets_.empty()))
550         cb_();
551 }
552
553 #undef LIBC_CALL
554 #undef LIBC_CALL_RV
555
556 ///////////////////////////////cc.e////////////////////////////////////////
557 #undef prefix_
558 //#include "Daemon.mpp"
559
560 \f
561 // Local Variables:
562 // mode: c++
563 // fill-column: 100
564 // comment-column: 40
565 // c-file-style: "senf"
566 // indent-tabs-mode: nil
567 // ispell-local-dictionary: "american"
568 // compile-command: "scons -u test"
569 // End: