4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 // Stefan Bund <g0dil@berlios.de>
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.
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.
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.
24 \brief Daemon non-inline non-template implementation */
30 #include <sys/types.h>
40 #include <boost/algorithm/string/predicate.hpp>
41 #include <boost/algorithm/string/trim.hpp>
42 #include <boost/format.hpp>
43 #include "../Exception.hh"
44 #include "../membind.hh"
45 #include "../Backtrace.hh"
46 #include "../signalnames.hh"
51 //#include "Daemon.mpp"
53 ///////////////////////////////cc.p////////////////////////////////////////
55 #define LIBC_CALL(fn, args) if (fn args < 0) \
56 SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
58 #define LIBC_CALL_RV(var, fn, args) \
59 int var (fn args); if (var < 0) SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
61 ///////////////////////////////////////////////////////////////////////////
64 prefix_ senf::Daemon::~Daemon()
66 if (pidfileCreated_) {
68 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
69 } catch (Exception e) {
70 // e << "; could not unlink " << pidfile_.c_str();
76 prefix_ void senf::Daemon::daemonize(bool v)
81 prefix_ bool senf::Daemon::daemon()
86 prefix_ int senf::Daemon::argc()
91 prefix_ char ** senf::Daemon::argv()
99 bool operator()(std::string const & str) const {
100 return str == "--no-daemon"
101 || boost::starts_with(str, std::string("--pid-file="))
102 || boost::starts_with(str, std::string("--console-log="));
107 prefix_ void senf::Daemon::removeDaemonArgs()
109 char ** last (std::remove_if(argv_+1, argv_+argc_, IsDaemonOpt()));
111 argc_ = last - argv_;
114 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
117 case StdOut : stdoutLog_ = path; break;
118 case StdErr : stderrLog_ = path; break;
119 case Both : stdoutLog_ = path; stderrLog_ = path; break;
124 prefix_ void senf::Daemon::openLog()
127 if (! stdoutLog_.empty()) {
128 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
130 SENF_THROW_SYSTEM_EXCEPTION("")
131 << " Could not open \"" << stdoutLog_ << "\" for redirecting stdout.";
134 if (stderrLog_ == stdoutLog_)
136 else if (! stderrLog_.empty()) {
137 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
139 SENF_THROW_SYSTEM_EXCEPTION("")
140 << " Could not open \"" << stderrLog_ << "\" for redirecting stderr.";
145 prefix_ void senf::Daemon::logReopen()
147 if (! stdoutLog_.empty()) {
148 int fd (::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
151 if (::dup2(fd, 1) < 0)
153 if (stderrLog_ == stdoutLog_) {
154 if (::dup2(fd, 2) < 0)
159 if (! stderrLog_.empty()) {
160 int fd (::open(stderrLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
163 if (::dup2(fd, 2) < 0)
170 (senf::log::CRITICAL)
171 ("log-file reopen failed: (" << errno << ") " << ::strerror(errno)) );
174 prefix_ void senf::Daemon::pidFile(std::string const & f)
180 bool signaled (false);
186 prefix_ void senf::Daemon::detach()
188 if (daemonize_ && ! detached_) {
190 // To ensure all data is written to the console log file in the correct order, we suspend
191 // execution here until the parent process tells us to continue via SIGUSR1: We block
192 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
193 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
194 // SIGUSR1 and reinstall the old signal mask and action.
197 ::sigemptyset(&usrsig);
198 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
199 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
200 struct ::sigaction oldact;
201 struct ::sigaction usract;
202 ::memset(&usract, 0, sizeof(usract));
203 usract.sa_handler = &waitusr;
204 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
205 ::sigset_t waitsig (oldsig);
206 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
208 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
209 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
210 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
211 LIBC_CALL( ::close, (nul) );
215 ::sigsuspend(&waitsig);
217 SENF_THROW_SYSTEM_EXCEPTION("::sigsuspend()");
220 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
221 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
228 /* Purposely *not* derived from std::exception */
229 struct DaemonExitException {
230 DaemonExitException(unsigned c) : code(c) {}
235 prefix_ void senf::Daemon::exit(unsigned code)
237 throw DaemonExitException(code);
240 prefix_ int senf::Daemon::start(int argc, char ** argv)
252 installSighandlers();
253 if (! pidfile_.empty()) {
255 pidfileCreated_ = true;
257 std::cerr << "PID file '" << pidfile_
258 << "' creation failed. Daemon running ?" << std::endl;
265 catch (DaemonExitException & e) {
271 catch (std::exception & e) {
272 std::cerr << "\n*** Fatal exception: " << e.what() << "\n" << std::endl;
276 std::cerr << "\n*** Fatal exception: (unknown)" << "\n" << std::endl;
285 prefix_ senf::Daemon & senf::Daemon::instance()
287 BOOST_ASSERT( instance_ );
291 ////////////////////////////////////////
294 prefix_ senf::Daemon::Daemon()
295 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
296 pidfileCreated_(false), detached_(false)
298 BOOST_ASSERT( ! instance_ );
302 senf::Daemon * senf::Daemon::instance_ (0);
304 ////////////////////////////////////////
307 prefix_ void senf::Daemon::configure()
309 for (int i (1); i<argc_; ++i) {
310 if (argv_[i] == std::string("--no-daemon"))
312 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
313 std::string arg (std::string(argv_[i]), 14u);
314 std::string::size_type komma (arg.find(','));
315 if (komma == std::string::npos) {
317 if (arg == std::string("none")) consoleLog("");
318 else if (!arg.empty()) consoleLog(arg);
320 std::string arg1 (arg,0,komma);
321 std::string arg2 (arg,komma+1);
324 if (arg1 == std::string("none")) consoleLog("",StdOut);
325 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
326 if (arg2 == std::string("none")) consoleLog("",StdErr);
327 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
330 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
331 pidFile(std::string(std::string(argv_[i]), 11u));
335 prefix_ void senf::Daemon::main()
342 prefix_ void senf::Daemon::init()
345 prefix_ void senf::Daemon::run()
348 prefix_ void senf::Daemon::fork()
353 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
354 LIBC_CALL( ::dup2, (nul, 0) );
355 LIBC_CALL( ::close, (nul) );
356 LIBC_CALL( ::pipe, (coutpipe) );
357 LIBC_CALL( ::pipe, (cerrpipe) );
359 // We need to block the SIGCHLD signal here so we don't miss it, if the child
363 ::sigemptyset(&cldsig);
364 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
365 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
367 LIBC_CALL_RV( pid, ::fork, () );
372 LIBC_CALL( ::dup2, (coutpipe[1],1) );
373 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
374 LIBC_CALL( ::close, (coutpipe[0]) );
375 LIBC_CALL( ::close, (coutpipe[1]) );
376 LIBC_CALL( ::close, (cerrpipe[0]) );
377 LIBC_CALL( ::close, (cerrpipe[1]) );
378 LIBC_CALL( ::setsid, () );
379 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
383 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
386 LIBC_CALL( ::close, (coutpipe[1]) );
387 LIBC_CALL( ::close, (cerrpipe[1]) );
389 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
395 prefix_ bool senf::Daemon::pidfileCreate()
397 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
398 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
399 // was some race condition, probably over NFS.
401 std::string tempname;
402 boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
405 char hostname[HOST_NAME_MAX+1];
406 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
407 hostname[HOST_NAME_MAX] = 0;
408 std::stringstream tempname_s;
409 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
410 tempname = tempname_s.str();
415 std::ofstream pidf (tempname.c_str());
417 SENF_THROW_SYSTEM_EXCEPTION("")
418 << " Could not open pidfile \"" << tempname << "\" for output.";
419 pidf << ::getpid() << std::endl;
421 SENF_THROW_SYSTEM_EXCEPTION("")
422 << " Could not write to pidfile \"" << tempname << "\".";
425 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
427 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % pidfile_ % tempname;
431 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
432 LIBC_CALL( ::unlink, (tempname.c_str()) );
433 return s.st_nlink == 2;
436 // pidfile exists. Check, whether the pid in the pidfile still exists.
439 std::ifstream pidf (pidfile_.c_str());
440 if ( ! (pidf >> old_pid)
442 || ::kill(old_pid, 0) >= 0
443 || errno == EPERM ) {
444 LIBC_CALL( ::unlink, (tempname.c_str()) );
449 // If we reach this point, the pid file exists but the process mentioned within the
450 // pid file does *not* exists. We assume, the pid file to be stale.
452 // I hope, the following procedure is without race condition: We remove our generated
453 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
454 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
455 // must have already created his hardlink. We then truncate the file and write our pid.
457 LIBC_CALL( ::unlink, (tempname.c_str() ));
458 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
460 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % tempname % pidfile_;
461 // Hmm ... the pidfile mysteriously disappeared ... try again.
467 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
468 if (s.st_nlink != 2) {
469 LIBC_CALL( ::unlink, (tempname.c_str()) );
475 std::ofstream pidf (tempname.c_str());
476 pidf << ::getpid() << std::endl;
479 LIBC_CALL( ::unlink, (tempname.c_str()) );
489 void fatalSignalsHandler(int sig, ::siginfo_t * info, void * arg)
491 // ::ucontext_t * ucontext = static_cast<ucontext_t*>(arg);
492 std::cerr << "\n" << "Signal " << senf::signalName(sig) << '(' << sig << ')'
496 std::cerr << "Invalid memory access at " << info->si_addr << "\n";
498 static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
499 unsigned nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
501 // Hack the callers address into the backtrace
502 // entries[1] = reinterpret_cast<void *>(ucontext->uc_mcontext.gregs[REG_EIP]);
504 std::cerr << "Backtrace:\n";
505 senf::formatBacktrace(std::cerr, entries, nEntries);
506 std::cerr << "-- \n";
508 if (sig != SIGUSR2) {
509 ::signal(sig, SIG_DFL);
510 ::kill(::getpid(), sig);
519 void sighupHandler(int sig)
521 senf::Daemon::instance().logReopen();
525 prefix_ void senf::Daemon::installSighandlers()
527 struct ::sigaction sa;
529 ::sigemptyset(&sa.sa_mask);
530 sa.sa_handler = &sighupHandler;
531 sa.sa_flags = SA_RESTART;
533 ::sigaction(SIGHUP, &sa, NULL);
535 sa.sa_handler = SIG_IGN;
536 ::sigaction(SIGPIPE, &sa, NULL);
539 sa.sa_sigaction = &fatalSignalsHandler;
540 sa.sa_flags = SA_RESTART | SA_SIGINFO;
542 ::sigaction(SIGILL, &sa, NULL);
543 ::sigaction(SIGTRAP, &sa, NULL);
544 ::sigaction(SIGABRT, &sa, NULL);
545 ::sigaction(SIGFPE, &sa, NULL);
546 ::sigaction(SIGBUS, &sa, NULL);
547 ::sigaction(SIGSEGV, &sa, NULL);
548 ::sigaction(SIGSTKFLT, &sa, NULL);
549 ::sigaction(SIGSYS, &sa, NULL);
550 ::sigaction(SIGUSR2, &sa, NULL);
554 ///////////////////////////////////////////////////////////////////////////
555 // senf::detail::DaemonWatcher
557 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
558 int stdout, int stderr)
559 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
560 stderr_(stderr), sigChld_(false),
561 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
562 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
564 coutForwarder_.addTarget(1);
566 coutForwarder_.addTarget(stdout_);
567 cerrForwarder_.addTarget(2);
569 cerrForwarder_.addTarget(stderr_);
572 prefix_ void senf::detail::DaemonWatcher::run()
574 Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
575 Scheduler::instance().process();
578 ////////////////////////////////////////
581 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
584 case 1 : coutpipe_ = -1; break;
585 case 2 : cerrpipe_ = -1; break;
588 if (coutpipe_ == -1 && cerrpipe_ == -1) {
590 childDied(); // does not return
591 if (::kill(childPid_, SIGUSR1) < 0)
592 if (errno != ESRCH) SENF_THROW_SYSTEM_EXCEPTION("::kill()");
593 Scheduler::instance().timeout(
594 Scheduler::instance().eventTime() + ClockService::seconds(1),
595 senf::membind(&DaemonWatcher::childOk, this));
599 prefix_ void senf::detail::DaemonWatcher::sigChld(siginfo_t const &)
602 if (coutpipe_ == -1 && cerrpipe_ == -1)
603 childDied(); // does not return
606 prefix_ void senf::detail::DaemonWatcher::childDied()
609 if (::waitpid(childPid_,&status,0) < 0) SENF_THROW_SYSTEM_EXCEPTION("::waitpid()");
610 if (WIFSIGNALED(status)) {
611 ::signal(WTERMSIG(status),SIG_DFL);
612 ::kill(::getpid(), WTERMSIG(status));
613 // should not be reached
616 if (WEXITSTATUS(status) == 0)
618 ::_exit(WEXITSTATUS(status));
621 prefix_ void senf::detail::DaemonWatcher::childOk()
623 Scheduler::instance().terminate();
626 ///////////////////////////////////////////////////////////////////////////
627 // senf::detail::DaemonWatcher::Forwarder
629 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
632 Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
636 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
639 Scheduler::instance().remove(src_);
641 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
642 if (i->offset >= buffer_.size())
643 Scheduler::instance().remove(i->fd);
646 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
648 Target target = { fd, 0 };
649 targets_.push_back(target);
652 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(int event)
658 n = ::read(src_,buf,1024);
660 if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::read()");
667 Scheduler::instance().remove(src_);
674 if (targets_.empty())
677 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
678 if (i->offset >= buffer_.size())
679 Scheduler::instance().add( i->fd,
680 boost::bind(&Forwarder::writeData, this, _1, i),
681 Scheduler::EV_WRITE );
683 buffer_.insert(buffer_.end(), buf, buf+n);
686 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(int event,
687 Targets::iterator target)
689 if (event != Scheduler::EV_WRITE) {
690 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
691 Scheduler::instance().remove(target->fd);
692 targets_.erase(target);
693 if (targets_.empty() && src_ == -1)
699 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
700 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
702 int w (::write(target->fd, buf, n));
704 if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::write()");
709 n = std::min_element(
710 targets_.begin(), targets_.end(),
711 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
713 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
715 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
718 if (target->offset >= buffer_.size())
719 Scheduler::instance().remove(target->fd);
720 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
727 ///////////////////////////////cc.e////////////////////////////////////////
729 //#include "Daemon.mpp"
735 // comment-column: 40
736 // c-file-style: "senf"
737 // indent-tabs-mode: nil
738 // ispell-local-dictionary: "american"
739 // compile-command: "scons -u test"