34f476a1b21f397885787b01a87c4abfe95a6b20
[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_) {
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 }
149
150 prefix_ int senf::Daemon::start(int argc, char const ** argv)
151 {
152     argc_ = argc;
153     argv_ = argv;
154
155 #   ifdef NDEBUG
156
157     try {
158
159 #   endif
160
161         configure();
162
163         if (daemonize_) {
164             openLog();
165             fork();
166         }
167         if (! pidfile_.empty() && ! pidfileCreate()) {
168             std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?" 
169                       << std::endl;
170             return 1;
171         }
172
173         main();
174
175 #   ifdef NDEBUG
176
177     }
178     catch (std::exception & e) {
179         std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
180         return 1;
181     }
182     catch (...) {
183         std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
184         return 1;
185     }
186
187 #   endif
188
189     return 0;
190 }
191
192 ////////////////////////////////////////
193 // protected members
194
195 prefix_ senf::Daemon::Daemon()
196     : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
197       detached_(false)
198 {}
199
200 ////////////////////////////////////////
201 // private members
202
203 prefix_ void senf::Daemon::configure()
204 {
205     for (int i (1); i<argc_; ++i) {
206         if (argv_[i] == std::string("--no-daemon"))
207             daemonize(false);
208         else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
209             std::string arg (std::string(argv_[i]), 14u);
210             std::string::size_type komma (arg.find(','));
211             if (komma == std::string::npos) {
212                 boost::trim(arg);
213                 consoleLog(arg);
214             } else {
215                 std::string arg1 (arg,0,komma);
216                 std::string arg2 (arg,komma+1);
217                 boost::trim(arg1);
218                 boost::trim(arg2);
219                 if (arg1 == std::string("none")) consoleLog("",StdOut);
220                 else if (! arg1.empty() )        consoleLog(arg1, StdOut);
221                 if (arg2 == std::string("none")) consoleLog("",StdErr);
222                 else if (! arg2.empty() )        consoleLog(arg2, StdErr);
223             }
224         }
225         else if (boost::starts_with(argv_[i], std::string("--pid-file="))) 
226             pidFile(std::string(std::string(argv_[i]), 11u));
227     }
228 }
229
230 prefix_ void senf::Daemon::main()
231 {
232     init();
233     detach();
234     run();
235 }
236
237 prefix_ void senf::Daemon::init()
238 {}
239
240 prefix_ void senf::Daemon::run()
241 {}
242
243 prefix_ void senf::Daemon::fork()
244 {
245     int coutpipe[2];
246     int cerrpipe[2];
247
248     LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
249     LIBC_CALL( ::dup2, (nul, 0) );
250     LIBC_CALL( ::close, (nul) );
251     LIBC_CALL( ::pipe, (coutpipe) );
252     LIBC_CALL( ::pipe, (cerrpipe) );
253
254     // We need to block the SIGCHLD signal here so we don't miss it, if the child
255     // dies immediately
256     ::sigset_t oldsig;
257     ::sigset_t cldsig;
258     ::sigemptyset(&cldsig);
259     LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
260     LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
261     
262     LIBC_CALL_RV( pid, ::fork, () );
263
264     if (pid == 0) {
265         // Daemon process
266
267         LIBC_CALL( ::dup2, (coutpipe[1],1) );
268         LIBC_CALL( ::dup2, (cerrpipe[1],2) );
269         LIBC_CALL( ::close, (coutpipe[0]) );
270         LIBC_CALL( ::close, (coutpipe[1]) );
271         LIBC_CALL( ::close, (cerrpipe[0]) );
272         LIBC_CALL( ::close, (cerrpipe[1]) );
273         LIBC_CALL( ::setsid, () );
274         LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
275         return;
276     }
277
278     // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
279     pidfile_ = "";
280     
281     LIBC_CALL( ::close, (coutpipe[1]) );
282     LIBC_CALL( ::close, (cerrpipe[1]) );
283
284     detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
285     watcher.run();
286
287     ::_exit(0);
288 }
289
290 prefix_ bool senf::Daemon::pidfileCreate()
291 {
292     // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
293     // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
294     // was some race condition, probably over NFS.
295
296     std::string tempname;
297
298     {
299         char hostname[HOST_NAME_MAX+1];
300         LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
301         hostname[HOST_NAME_MAX] = 0;
302         std::stringstream tempname_s;
303         tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
304         tempname = tempname_s.str();
305     }
306
307     while (1) {
308         {
309             std::ofstream pidf (tempname.c_str());
310             pidf << ::getpid() << std::endl;
311         }
312
313         if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
314             if (errno != EEXIST) 
315                 throwErrno("::link()");
316         }
317         else {
318             struct ::stat s;
319             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
320             LIBC_CALL( ::unlink, (tempname.c_str()) );
321             return s.st_nlink == 2;
322         }
323
324         // pidfile exists. Check, whether the pid in the pidfile still exists.
325         {
326             int old_pid (-1);
327             std::ifstream pidf (pidfile_.c_str());
328             if ( ! (pidf >> old_pid)
329                  || old_pid < 0 
330                  || ::kill(old_pid, 0) >= 0 
331                  || errno == EPERM )
332                 return false;
333         }
334
335         // If we reach this point, the pid file exists but the process mentioned within the
336         // pid file does *not* exists. We assume, the pid file to be stale.
337
338         // I hope, the following procedure is without race condition: We remove our generated
339         // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
340         // the hard-link count of this file is 2. If it is not, we terminate, since someone else
341         // must have already created his hardlink. We then truncate the file and write our pid.
342
343         LIBC_CALL( ::unlink, (tempname.c_str() ));
344         if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
345             if (errno != ENOENT) throwErrno("::link()");
346             // Hmm ... the pidfile mysteriously disappeared ... try again.
347             continue;
348         }
349
350         {
351             struct ::stat s;
352             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
353             if (s.st_nlink != 2) {
354                 LIBC_CALL( ::unlink, (tempname.c_str()) );
355                 return false;
356             }
357         }
358         
359         {
360             std::ofstream pidf (tempname.c_str());
361             pidf << ::getpid() << std::endl;
362         }
363
364         LIBC_CALL( ::unlink, (tempname.c_str()) );
365         break;
366     }
367     return true;
368 }
369
370 ///////////////////////////////////////////////////////////////////////////
371 // senf::detail::DaemonWatcher
372
373 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
374                                                    int stdout, int stderr)
375     : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
376       stderr_(stderr), sigChld_(false),
377       coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)), 
378       cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2)) 
379 {
380     coutForwarder_.addTarget(1);
381     if (stdout_ >= 0)
382         coutForwarder_.addTarget(stdout_);
383     cerrForwarder_.addTarget(2);
384     if (stderr_ >= 0)
385         cerrForwarder_.addTarget(stderr_);
386 }
387
388 prefix_ void senf::detail::DaemonWatcher::run()
389 {
390     Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
391     Scheduler::instance().process();
392 }
393
394 ////////////////////////////////////////
395 // private members
396
397 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
398 {
399     switch (id) {
400     case 1 : coutpipe_ = -1; break;
401     case 2 : cerrpipe_ = -1; break;
402     }
403
404     if (coutpipe_ == -1 && cerrpipe_ == -1) {
405         if (sigChld_)
406             childDied(); // does not return
407         if (::kill(childPid_, SIGUSR1) < 0)
408             if (errno != ESRCH) throwErrno("::kill()");
409         Scheduler::instance().timeout(
410             Scheduler::instance().eventTime() + ClockService::seconds(1),
411             senf::membind(&DaemonWatcher::childOk, this));
412     }
413 }
414
415 prefix_ void senf::detail::DaemonWatcher::sigChld()
416 {
417     sigChld_ = true;
418     if (coutpipe_ == -1 && cerrpipe_ == -1)
419         childDied(); // does not return
420 }
421
422 prefix_ void senf::detail::DaemonWatcher::childDied()
423 {
424     int status (0);
425     if (::waitpid(childPid_,&status,0) < 0) throwErrno("::waitpid()");
426     if (WIFSIGNALED(status)) {
427         ::signal(WTERMSIG(status),SIG_DFL);
428         ::kill(::getpid(), WTERMSIG(status));
429         // should not be reached
430         ::_exit(1);
431     }
432     if (WEXITSTATUS(status) == 0)
433         ::_exit(1);
434     ::_exit(WEXITSTATUS(status));
435 }
436
437 prefix_ void senf::detail::DaemonWatcher::childOk()
438 {
439     Scheduler::instance().terminate();
440 }
441
442 ///////////////////////////////////////////////////////////////////////////
443 // senf::detail::DaemonWatcher::Forwarder
444
445 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
446     : src_(src), cb_(cb)
447 {
448     Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
449                               Scheduler::EV_READ);
450 }
451
452 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
453 {
454     if (src_ != -1)
455         Scheduler::instance().remove(src_);
456     
457     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
458         if (i->offset >= buffer_.size())
459             Scheduler::instance().remove(i->fd);
460 }
461
462 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
463 {
464     Target target = { fd, 0 };
465     targets_.push_back(target);
466 }
467
468 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
469 {
470     char buf[1024];
471     int n (0);
472
473     while (1) {
474         n = ::read(src_,buf,1024);
475         if (n<0) {
476             if (errno != EINTR) throwErrno("::read()");
477         } else 
478             break;
479     }
480
481     if (n == 0) {
482         // Hangup
483         Scheduler::instance().remove(src_);
484         if (buffer_.empty())
485             cb_(); 
486         src_ = -1;
487         return;
488     }
489
490     if (targets_.empty())
491         return;
492
493     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
494         if (i->offset >= buffer_.size())
495             Scheduler::instance().add( i->fd, 
496                                        boost::bind(&Forwarder::writeData, this, _1, i),
497                                        Scheduler::EV_WRITE );
498
499     buffer_.insert(buffer_.end(), buf, buf+n);
500 }
501
502 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
503                                                                Targets::iterator target)
504 {    
505     if (event != Scheduler::EV_WRITE) {
506         // Broken pipe while writing data ? Not much, we can do here, we just drop the data
507         Scheduler::instance().remove(target->fd);
508         targets_.erase(target);
509         if (targets_.empty() && src_ == -1)
510             cb_();
511         return;
512     }
513
514     char buf[1024];
515     int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
516     std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
517
518     int w (::write(target->fd, buf, n));
519     if (w < 0) {
520         if (errno != EINTR) throwErrno("::write()");
521         return;
522     }
523     target->offset += w;
524
525     n = std::min_element(
526         targets_.begin(), targets_.end(),
527         boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
528
529     buffer_.erase(buffer_.begin(), buffer_.begin()+n);
530
531     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
532         i->offset -= n;
533
534     if (target->offset >= buffer_.size())
535         Scheduler::instance().remove(target->fd);
536     if (src_ == -1 && (buffer_.empty() || targets_.empty()))
537         cb_();
538 }
539
540 #undef LIBC_CALL
541 #undef LIBC_CALL_RV
542
543 ///////////////////////////////cc.e////////////////////////////////////////
544 #undef prefix_
545 //#include "Daemon.mpp"
546
547 \f
548 // Local Variables:
549 // mode: c++
550 // fill-column: 100
551 // comment-column: 40
552 // c-file-style: "senf"
553 // indent-tabs-mode: nil
554 // ispell-local-dictionary: "american"
555 // compile-command: "scons -u test"
556 // End: