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_)
137 else if (! stderrLog_.empty()) {
138 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
140 SENF_THROW_SYSTEM_EXCEPTION("")
141 << " Could not open \"" << stderrLog_ << "\" for redirecting stderr.";
146 prefix_ void senf::Daemon::logReopen()
148 if (! stdoutLog_.empty()) {
149 int fd (::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
152 if (::dup2(fd, 1) < 0)
154 if (stderrLog_ == stdoutLog_) {
155 if (::dup2(fd, 2) < 0)
160 if (! stderrLog_.empty()) {
161 int fd (::open(stderrLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
164 if (::dup2(fd, 2) < 0)
171 (senf::log::CRITICAL)
172 ("log-file reopen failed: (" << errno << ") " << ::strerror(errno)) );
175 prefix_ void senf::Daemon::pidFile(std::string const & f)
181 bool signaled (false);
187 prefix_ void senf::Daemon::detach()
189 if (daemonize_ && ! detached_) {
191 // To ensure all data is written to the console log file in the correct order, we suspend
192 // execution here until the parent process tells us to continue via SIGUSR1: We block
193 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
194 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
195 // SIGUSR1 and reinstall the old signal mask and action.
198 ::sigemptyset(&usrsig);
199 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
200 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
201 struct ::sigaction oldact;
202 struct ::sigaction usract;
203 ::memset(&usract, 0, sizeof(usract));
204 usract.sa_handler = &waitusr;
205 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
206 ::sigset_t waitsig (oldsig);
207 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
209 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
210 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
211 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
212 LIBC_CALL( ::close, (nul) );
216 ::sigsuspend(&waitsig);
218 SENF_THROW_SYSTEM_EXCEPTION("::sigsuspend()");
221 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
222 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
229 /* Purposely *not* derived from std::exception */
230 struct DaemonExitException {
231 DaemonExitException(unsigned c) : code(c) {}
236 prefix_ void senf::Daemon::exit(unsigned code)
238 throw DaemonExitException(code);
241 prefix_ int senf::Daemon::start(int argc, char const ** argv)
253 installSighandlers();
254 if (! pidfile_.empty()) {
256 pidfileCreated_ = true;
258 std::cerr << "PID file '" << pidfile_
259 << "' creation failed. Daemon running ?" << std::endl;
266 catch (DaemonExitException & e) {
272 catch (std::exception & e) {
273 std::cerr << "\n*** Fatal exception: " << e.what() << "\n" << std::endl;
277 std::cerr << "\n*** Fatal exception: (unknown)" << "\n" << std::endl;
286 prefix_ senf::Daemon & senf::Daemon::instance()
288 BOOST_ASSERT( instance_ );
292 ////////////////////////////////////////
295 prefix_ senf::Daemon::Daemon()
296 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
297 pidfileCreated_(false), detached_(false)
299 BOOST_ASSERT( ! instance_ );
303 senf::Daemon * senf::Daemon::instance_ (0);
305 ////////////////////////////////////////
308 prefix_ void senf::Daemon::configure()
310 for (int i (1); i<argc_; ++i) {
311 if (argv_[i] == std::string("--no-daemon"))
313 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
314 std::string arg (std::string(argv_[i]), 14u);
315 std::string::size_type komma (arg.find(','));
316 if (komma == std::string::npos) {
318 if (arg == std::string("none")) consoleLog("");
319 else if (!arg.empty()) consoleLog(arg);
321 std::string arg1 (arg,0,komma);
322 std::string arg2 (arg,komma+1);
325 if (arg1 == std::string("none")) consoleLog("",StdOut);
326 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
327 if (arg2 == std::string("none")) consoleLog("",StdErr);
328 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
331 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
332 pidFile(std::string(std::string(argv_[i]), 11u));
336 prefix_ void senf::Daemon::main()
343 prefix_ void senf::Daemon::init()
346 prefix_ void senf::Daemon::run()
349 prefix_ void senf::Daemon::fork()
354 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
355 LIBC_CALL( ::dup2, (nul, 0) );
356 LIBC_CALL( ::close, (nul) );
357 LIBC_CALL( ::pipe, (coutpipe) );
358 LIBC_CALL( ::pipe, (cerrpipe) );
360 // We need to block the SIGCHLD signal here so we don't miss it, if the child
364 ::sigemptyset(&cldsig);
365 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
366 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
368 if (! senf::scheduler::empty() )
372 "Scheduler not empty before fork(). THIS MUST NOT HAPPEN.\n"
373 "The scheduler will be reinitialized by the fork() and lose all registrations.\n"
377 LIBC_CALL_RV( pid, ::fork, () );
382 LIBC_CALL( ::dup2, (coutpipe[1],1) );
383 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
384 LIBC_CALL( ::close, (coutpipe[0]) );
385 LIBC_CALL( ::close, (coutpipe[1]) );
386 LIBC_CALL( ::close, (cerrpipe[0]) );
387 LIBC_CALL( ::close, (cerrpipe[1]) );
388 LIBC_CALL( ::setsid, () );
389 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
391 senf::scheduler::restart();
395 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
398 LIBC_CALL( ::close, (coutpipe[1]) );
399 LIBC_CALL( ::close, (cerrpipe[1]) );
401 senf::scheduler::restart();
403 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
409 prefix_ bool senf::Daemon::pidfileCreate()
411 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
412 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
413 // was some race condition, probably over NFS.
415 std::string tempname;
416 boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
419 char hostname[HOST_NAME_MAX+1];
420 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
421 hostname[HOST_NAME_MAX] = 0;
422 std::stringstream tempname_s;
423 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
424 tempname = tempname_s.str();
429 std::ofstream pidf (tempname.c_str());
431 SENF_THROW_SYSTEM_EXCEPTION("")
432 << " Could not open pidfile \"" << tempname << "\" for output.";
433 pidf << ::getpid() << std::endl;
435 SENF_THROW_SYSTEM_EXCEPTION("")
436 << " Could not write to pidfile \"" << tempname << "\".";
439 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
441 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % pidfile_ % tempname;
445 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
446 LIBC_CALL( ::unlink, (tempname.c_str()) );
447 return s.st_nlink == 2;
450 // pidfile exists. Check, whether the pid in the pidfile still exists.
453 std::ifstream pidf (pidfile_.c_str());
454 if ( ! (pidf >> old_pid)
456 || ::kill(old_pid, 0) >= 0
457 || errno == EPERM ) {
458 LIBC_CALL( ::unlink, (tempname.c_str()) );
463 // If we reach this point, the pid file exists but the process mentioned within the
464 // pid file does *not* exists. We assume, the pid file to be stale.
466 // I hope, the following procedure is without race condition: We remove our generated
467 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
468 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
469 // must have already created his hardlink. We then truncate the file and write our pid.
471 LIBC_CALL( ::unlink, (tempname.c_str() ));
472 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
474 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % tempname % pidfile_;
475 // Hmm ... the pidfile mysteriously disappeared ... try again.
481 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
482 if (s.st_nlink != 2) {
483 LIBC_CALL( ::unlink, (tempname.c_str()) );
489 std::ofstream pidf (tempname.c_str());
490 pidf << ::getpid() << std::endl;
493 LIBC_CALL( ::unlink, (tempname.c_str()) );
503 void fatalSignalsHandler(int sig, ::siginfo_t * info, void * arg)
505 // ::ucontext_t * ucontext = static_cast<ucontext_t*>(arg);
506 std::cerr << "\n" << "Signal " << senf::signalName(sig) << '(' << sig << ')'
510 std::cerr << "Invalid memory access at " << info->si_addr << "\n";
512 static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
513 unsigned nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
515 // Hack the callers address into the backtrace
516 // entries[1] = reinterpret_cast<void *>(ucontext->uc_mcontext.gregs[REG_EIP]);
518 std::cerr << "Backtrace:\n";
519 senf::formatBacktrace(std::cerr, entries, nEntries);
520 std::cerr << "-- \n";
522 if (sig != SIGUSR2) {
523 ::signal(sig, SIG_DFL);
524 ::kill(::getpid(), sig);
533 void sighupHandler(int sig)
535 senf::Daemon::instance().logReopen();
539 prefix_ void senf::Daemon::installSighandlers()
541 struct ::sigaction sa;
543 ::sigemptyset(&sa.sa_mask);
544 sa.sa_handler = &sighupHandler;
545 sa.sa_flags = SA_RESTART;
547 ::sigaction(SIGHUP, &sa, NULL);
549 sa.sa_handler = SIG_IGN;
550 ::sigaction(SIGPIPE, &sa, NULL);
553 sa.sa_sigaction = &fatalSignalsHandler;
554 sa.sa_flags = SA_RESTART | SA_SIGINFO;
556 ::sigaction(SIGILL, &sa, NULL);
557 ::sigaction(SIGTRAP, &sa, NULL);
558 ::sigaction(SIGABRT, &sa, NULL);
559 ::sigaction(SIGFPE, &sa, NULL);
560 ::sigaction(SIGBUS, &sa, NULL);
561 ::sigaction(SIGSEGV, &sa, NULL);
562 ::sigaction(SIGSTKFLT, &sa, NULL);
563 ::sigaction(SIGSYS, &sa, NULL);
564 ::sigaction(SIGUSR2, &sa, NULL);
568 ///////////////////////////////////////////////////////////////////////////
569 // senf::detail::DaemonWatcher
571 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
572 int stdout, int stderr)
573 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
574 stderr_(stderr), sigChld_(false),
575 cldSignal_ (SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this)),
576 timer_ ("senf::detail::DaemonWatcher::childOk", senf::membind(&DaemonWatcher::childOk, this)),
577 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
578 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
580 coutForwarder_.addTarget(1);
582 coutForwarder_.addTarget(stdout_);
583 cerrForwarder_.addTarget(2);
585 cerrForwarder_.addTarget(stderr_);
588 prefix_ void senf::detail::DaemonWatcher::run()
590 scheduler::process();
593 ////////////////////////////////////////
596 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
599 case 1 : coutpipe_ = -1; break;
600 case 2 : cerrpipe_ = -1; break;
603 if (coutpipe_ == -1 && cerrpipe_ == -1) {
605 childDied(); // does not return
606 if (::kill(childPid_, SIGUSR1) < 0 && errno != ESRCH)
607 SENF_THROW_SYSTEM_EXCEPTION("::kill()");
608 timer_.timeout(scheduler::eventTime() + ClockService::seconds(1));
612 prefix_ void senf::detail::DaemonWatcher::sigChld(siginfo_t const &)
615 if (coutpipe_ == -1 && cerrpipe_ == -1)
616 childDied(); // does not return
619 prefix_ void senf::detail::DaemonWatcher::childDied()
622 if (::waitpid(childPid_,&status,0) < 0) SENF_THROW_SYSTEM_EXCEPTION("::waitpid()");
623 if (WIFSIGNALED(status)) {
624 ::signal(WTERMSIG(status),SIG_DFL);
625 ::kill(::getpid(), WTERMSIG(status));
626 // should not be reached
629 if (WEXITSTATUS(status) == 0)
631 ::_exit(WEXITSTATUS(status));
634 prefix_ void senf::detail::DaemonWatcher::childOk()
636 scheduler::terminate();
639 ///////////////////////////////////////////////////////////////////////////
640 // senf::detail::DaemonWatcher::Forwarder
642 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
643 : src_(src), cb_(cb),
644 readevent_("senf::detail::DaemonWatcher::Forwarder::readevent", senf::membind(&Forwarder::readData, this),
645 src_, scheduler::FdEvent::EV_READ)
648 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
650 targets_.clear_and_destroy(DestroyDelete());
653 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
655 targets_.push_back(*(new Target(*this, fd)));
658 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(int event)
664 n = ::read(src_,buf,1024);
667 SENF_THROW_SYSTEM_EXCEPTION("::read()");
677 readevent_.disable();
681 if (targets_.empty())
684 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
685 if (i->offset >= buffer_.size())
686 i->writeevent.enable();
688 buffer_.insert(buffer_.end(), buf, buf+n);
691 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(int event, Target * target)
693 if (event != scheduler::FdEvent::EV_WRITE) {
694 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
695 targets_.erase_and_destroy(Targets::current(*target),DestroyDelete());
696 if (targets_.empty() && src_ == -1)
702 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
703 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
705 int w (::write(target->fd, buf, n));
707 if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::write()");
712 n = std::min_element(
713 targets_.begin(), targets_.end(),
714 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
716 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
718 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
721 if (target->offset >= buffer_.size())
722 target->writeevent.disable();
723 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
730 ///////////////////////////////cc.e////////////////////////////////////////
732 //#include "Daemon.mpp"
738 // comment-column: 40
739 // c-file-style: "senf"
740 // indent-tabs-mode: nil
741 // ispell-local-dictionary: "american"
742 // compile-command: "scons -u test"