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>
41 #include <boost/algorithm/string/predicate.hpp>
42 #include <boost/algorithm/string/trim.hpp>
43 #include <boost/format.hpp>
44 #include "../Exception.hh"
45 #include "../membind.hh"
46 #include "../Backtrace.hh"
47 #include "../signalnames.hh"
52 //#include "Daemon.mpp"
54 ///////////////////////////////cc.p////////////////////////////////////////
56 #define LIBC_CALL(fn, args) if (fn args < 0) \
57 SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
59 #define LIBC_CALL_RV(var, fn, args) \
60 int var (fn args); if (var < 0) SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
62 ///////////////////////////////////////////////////////////////////////////
65 prefix_ senf::Daemon::~Daemon()
67 if (pidfileCreated_) {
69 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
70 } catch (Exception e) {
71 // e << "; could not unlink " << pidfile_.c_str();
77 prefix_ void senf::Daemon::daemonize(bool v)
82 prefix_ bool senf::Daemon::daemon()
87 prefix_ int senf::Daemon::argc()
92 prefix_ char const ** senf::Daemon::argv()
100 bool operator()(std::string const & str) const {
101 return str == "--no-daemon"
102 || boost::starts_with(str, std::string("--pid-file="))
103 || boost::starts_with(str, std::string("--console-log="));
108 prefix_ void senf::Daemon::removeDaemonArgs()
110 char const ** last (std::remove_if(argv_+1, argv_+argc_, IsDaemonOpt()));
112 argc_ = last - argv_;
115 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
118 case StdOut : stdoutLog_ = path; break;
119 case StdErr : stderrLog_ = path; break;
120 case Both : stdoutLog_ = path; stderrLog_ = path; break;
125 prefix_ void senf::Daemon::openLog()
128 if (! stdoutLog_.empty()) {
129 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
131 SENF_THROW_SYSTEM_EXCEPTION("")
132 << " Could not open \"" << stdoutLog_ << "\" for redirecting stdout.";
135 if (stderrLog_ == stdoutLog_) {
138 SENF_THROW_SYSTEM_EXCEPTION("::dup()");
140 else if (! stderrLog_.empty()) {
141 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
143 SENF_THROW_SYSTEM_EXCEPTION("")
144 << " Could not open \"" << stderrLog_ << "\" for redirecting stderr.";
149 prefix_ void senf::Daemon::logReopen()
151 if (! stdoutLog_.empty()) {
152 int fd (::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
155 if (::dup2(fd, 1) < 0)
157 if (stderrLog_ == stdoutLog_) {
158 if (::dup2(fd, 2) < 0)
163 if (! stderrLog_.empty()) {
164 int fd (::open(stderrLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
167 if (::dup2(fd, 2) < 0)
174 (senf::log::CRITICAL)
175 ("log-file reopen failed: (" << errno << ") " << ::strerror(errno)) );
178 prefix_ void senf::Daemon::pidFile(std::string const & f)
184 bool signaled (false);
190 prefix_ void senf::Daemon::detach()
192 if (daemonize_ && ! detached_) {
194 // To ensure all data is written to the console log file in the correct order, we suspend
195 // execution here until the parent process tells us to continue via SIGUSR1: We block
196 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
197 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
198 // SIGUSR1 and reinstall the old signal mask and action.
201 ::sigemptyset(&usrsig);
202 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
203 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
204 struct ::sigaction oldact;
205 struct ::sigaction usract;
206 ::memset(&usract, 0, sizeof(usract));
207 usract.sa_handler = &waitusr;
208 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
209 ::sigset_t waitsig (oldsig);
210 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
212 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
213 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
214 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
215 LIBC_CALL( ::close, (nul) );
219 ::sigsuspend(&waitsig);
221 SENF_THROW_SYSTEM_EXCEPTION("::sigsuspend()");
224 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
225 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
232 /* Purposely *not* derived from std::exception */
233 struct DaemonExitException {
234 DaemonExitException(unsigned c) : code(c) {}
239 prefix_ void senf::Daemon::exit(unsigned code)
241 throw DaemonExitException(code);
244 prefix_ int senf::Daemon::start(int argc, char const ** argv)
256 installSighandlers();
257 if (! pidfile_.empty()) {
259 pidfileCreated_ = true;
261 std::cerr << "PID file '" << pidfile_
262 << "' creation failed. Daemon running ?" << std::endl;
269 catch (DaemonExitException & e) {
275 catch (std::exception & e) {
276 std::cerr << "\n*** Fatal exception: " << e.what() << "\n" << std::endl;
280 std::cerr << "\n*** Fatal exception: (unknown)" << "\n" << std::endl;
289 prefix_ senf::Daemon & senf::Daemon::instance()
291 BOOST_ASSERT( instance_ );
295 ////////////////////////////////////////
298 prefix_ senf::Daemon::Daemon()
299 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
300 pidfileCreated_(false), detached_(false)
302 BOOST_ASSERT( ! instance_ );
306 senf::Daemon * senf::Daemon::instance_ (0);
308 ////////////////////////////////////////
311 prefix_ void senf::Daemon::configure()
313 // int i (not unsigned) since argc_ is int ...
314 for (int i (1); i<argc_; ++i) {
315 if (argv_[i] == std::string("--no-daemon"))
317 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
318 std::string arg (std::string(argv_[i]), 14u);
319 std::string::size_type komma (arg.find(','));
320 if (komma == std::string::npos) {
322 if (arg == std::string("none")) consoleLog("");
323 else if (!arg.empty()) consoleLog(arg);
325 std::string arg1 (arg,0,komma);
326 std::string arg2 (arg,komma+1);
329 if (arg1 == std::string("none")) consoleLog("",StdOut);
330 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
331 if (arg2 == std::string("none")) consoleLog("",StdErr);
332 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
335 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
336 pidFile(std::string(std::string(argv_[i]), 11u));
340 prefix_ void senf::Daemon::main()
347 prefix_ void senf::Daemon::init()
350 prefix_ void senf::Daemon::run()
353 prefix_ void senf::Daemon::fork()
358 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
359 LIBC_CALL( ::dup2, (nul, 0) );
360 LIBC_CALL( ::close, (nul) );
361 LIBC_CALL( ::pipe, (coutpipe) );
362 LIBC_CALL( ::pipe, (cerrpipe) );
364 // We need to block the SIGCHLD signal here so we don't miss it, if the child
368 ::sigemptyset(&cldsig);
369 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
370 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
372 if (! senf::scheduler::empty() )
376 "Scheduler not empty before fork(). THIS MUST NOT HAPPEN.\n"
377 "The scheduler will be reinitialized by the fork() and lose all registrations.\n"
381 LIBC_CALL_RV( pid, ::fork, () );
386 LIBC_CALL( ::dup2, (coutpipe[1],1) );
387 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
388 LIBC_CALL( ::close, (coutpipe[0]) );
389 LIBC_CALL( ::close, (coutpipe[1]) );
390 LIBC_CALL( ::close, (cerrpipe[0]) );
391 LIBC_CALL( ::close, (cerrpipe[1]) );
392 LIBC_CALL( ::setsid, () );
393 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
395 senf::scheduler::restart();
399 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
402 LIBC_CALL( ::close, (coutpipe[1]) );
403 LIBC_CALL( ::close, (cerrpipe[1]) );
405 senf::scheduler::restart();
407 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
413 prefix_ bool senf::Daemon::pidfileCreate()
415 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
416 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
417 // was some race condition, probably over NFS.
419 std::string tempname;
420 boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
423 char hostname[HOST_NAME_MAX+1];
424 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
425 hostname[HOST_NAME_MAX] = 0;
426 std::stringstream tempname_s;
427 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
428 tempname = tempname_s.str();
433 std::ofstream pidf (tempname.c_str());
435 SENF_THROW_SYSTEM_EXCEPTION("")
436 << " Could not open pidfile \"" << tempname << "\" for output.";
437 pidf << ::getpid() << std::endl;
439 SENF_THROW_SYSTEM_EXCEPTION("")
440 << " Could not write to pidfile \"" << tempname << "\".";
443 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
445 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % pidfile_ % tempname;
449 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
450 LIBC_CALL( ::unlink, (tempname.c_str()) );
451 return s.st_nlink == 2;
454 // pidfile exists. Check, whether the pid in the pidfile still exists.
457 std::ifstream pidf (pidfile_.c_str());
458 if ( ! (pidf >> old_pid)
460 || ::kill(old_pid, 0) >= 0
461 || errno == EPERM ) {
462 LIBC_CALL( ::unlink, (tempname.c_str()) );
467 // If we reach this point, the pid file exists but the process mentioned within the
468 // pid file does *not* exists. We assume, the pid file to be stale.
470 // I hope, the following procedure is without race condition: We remove our generated
471 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
472 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
473 // must have already created his hardlink. We then truncate the file and write our pid.
475 LIBC_CALL( ::unlink, (tempname.c_str() ));
476 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
478 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % tempname % pidfile_;
479 // Hmm ... the pidfile mysteriously disappeared ... try again.
485 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
486 if (s.st_nlink != 2) {
487 LIBC_CALL( ::unlink, (tempname.c_str()) );
493 std::ofstream pidf (tempname.c_str());
494 pidf << ::getpid() << std::endl;
497 LIBC_CALL( ::unlink, (tempname.c_str()) );
507 void fatalSignalsHandler(int sig, ::siginfo_t * info, void * arg)
509 // ::ucontext_t * ucontext = static_cast<ucontext_t*>(arg);
510 std::cerr << "\n" << "Signal " << senf::signalName(sig) << '(' << sig << ')'
514 std::cerr << "Invalid memory access at " << info->si_addr << "\n";
516 static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
517 unsigned nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
519 // Hack the callers address into the backtrace
520 // entries[1] = reinterpret_cast<void *>(ucontext->uc_mcontext.gregs[REG_EIP]);
522 std::cerr << "Backtrace:\n";
523 senf::formatBacktrace(std::cerr, entries, nEntries);
524 std::cerr << "-- \n";
526 if (sig != SIGUSR2) {
527 ::signal(sig, SIG_DFL);
528 ::kill(::getpid(), sig);
537 void sighupHandler(int sig)
539 senf::Daemon::instance().logReopen();
543 prefix_ void senf::Daemon::installSighandlers()
545 struct ::sigaction sa;
547 ::sigemptyset(&sa.sa_mask);
548 sa.sa_handler = &sighupHandler;
549 sa.sa_flags = SA_RESTART;
551 ::sigaction(SIGHUP, &sa, NULL);
553 sa.sa_handler = SIG_IGN;
554 ::sigaction(SIGPIPE, &sa, NULL);
557 sa.sa_sigaction = &fatalSignalsHandler;
558 sa.sa_flags = SA_RESTART | SA_SIGINFO;
560 ::sigaction(SIGILL, &sa, NULL);
561 ::sigaction(SIGTRAP, &sa, NULL);
562 ::sigaction(SIGABRT, &sa, NULL);
563 ::sigaction(SIGFPE, &sa, NULL);
564 ::sigaction(SIGBUS, &sa, NULL);
565 ::sigaction(SIGSEGV, &sa, NULL);
566 ::sigaction(SIGSTKFLT, &sa, NULL);
567 ::sigaction(SIGSYS, &sa, NULL);
568 ::sigaction(SIGUSR2, &sa, NULL);
572 ///////////////////////////////////////////////////////////////////////////
573 // senf::detail::DaemonWatcher
575 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
576 int stdout, int stderr)
577 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
578 stderr_(stderr), sigChld_(false),
579 cldSignal_ (SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this)),
580 timer_ ("senf::detail::DaemonWatcher::childOk", senf::membind(&DaemonWatcher::childOk, this)),
581 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
582 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
584 coutForwarder_.addTarget(1);
586 coutForwarder_.addTarget(stdout_);
587 cerrForwarder_.addTarget(2);
589 cerrForwarder_.addTarget(stderr_);
592 prefix_ void senf::detail::DaemonWatcher::run()
594 scheduler::process();
597 ////////////////////////////////////////
600 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
603 case 1 : coutpipe_ = -1; break;
604 case 2 : cerrpipe_ = -1; break;
607 if (coutpipe_ == -1 && cerrpipe_ == -1) {
609 childDied(); // does not return
610 if (::kill(childPid_, SIGUSR1) < 0 && errno != ESRCH)
611 SENF_THROW_SYSTEM_EXCEPTION("::kill()");
612 timer_.timeout(scheduler::eventTime() + ClockService::seconds(1));
616 prefix_ void senf::detail::DaemonWatcher::sigChld(siginfo_t const &)
619 if (coutpipe_ == -1 && cerrpipe_ == -1)
620 childDied(); // does not return
623 prefix_ void senf::detail::DaemonWatcher::childDied()
626 if (::waitpid(childPid_,&status,0) < 0) SENF_THROW_SYSTEM_EXCEPTION("::waitpid()");
627 if (WIFSIGNALED(status)) {
628 ::signal(WTERMSIG(status),SIG_DFL);
629 ::kill(::getpid(), WTERMSIG(status));
630 // should not be reached
633 if (WEXITSTATUS(status) == 0)
635 ::_exit(WEXITSTATUS(status));
638 prefix_ void senf::detail::DaemonWatcher::childOk()
640 scheduler::terminate();
643 ///////////////////////////////////////////////////////////////////////////
644 // senf::detail::DaemonWatcher::Forwarder
646 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
647 : src_(src), cb_(cb),
648 readevent_("senf::detail::DaemonWatcher::Forwarder::readevent", senf::membind(&Forwarder::readData, this),
649 src_, scheduler::FdEvent::EV_READ)
652 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
654 targets_.clear_and_destroy(DestroyDelete());
657 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
659 targets_.push_back(*(new Target(*this, fd)));
662 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(int event)
668 n = ::read(src_,buf,1024);
671 SENF_THROW_SYSTEM_EXCEPTION("::read()");
681 readevent_.disable();
685 if (targets_.empty())
688 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
689 if (i->offset >= buffer_.size())
690 i->writeevent.enable();
692 buffer_.insert(buffer_.end(), buf, buf+n);
695 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(int event, Target * target)
697 if (event != scheduler::FdEvent::EV_WRITE) {
698 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
699 targets_.erase_and_destroy(Targets::current(*target),DestroyDelete());
700 if (targets_.empty() && src_ == -1)
706 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
707 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
709 int w (::write(target->fd, buf, n));
711 if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::write()");
716 n = std::min_element(
717 targets_.begin(), targets_.end(),
718 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
720 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
722 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
725 if (target->offset >= buffer_.size())
726 target->writeevent.disable();
727 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
734 ///////////////////////////////cc.e////////////////////////////////////////
736 //#include "Daemon.mpp"
742 // comment-column: 40
743 // c-file-style: "senf"
744 // indent-tabs-mode: nil
745 // ispell-local-dictionary: "american"
746 // compile-command: "scons -u test"