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 <senf/Utils/Exception.hh>
45 #include <senf/Utils/membind.hh>
46 #include <senf/Utils/Backtrace.hh>
47 #include <senf/Utils/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_.empty()) {
136 if (stderrLog_ == stdoutLog_) {
139 SENF_THROW_SYSTEM_EXCEPTION("::dup()");
142 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
144 SENF_THROW_SYSTEM_EXCEPTION("")
145 << " Could not open \"" << stderrLog_ << "\" for redirecting stderr.";
151 prefix_ void senf::Daemon::logReopen()
153 if (! stdoutLog_.empty()) {
154 int fd (::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
157 if (::dup2(fd, 1) < 0)
159 if (stderrLog_ == stdoutLog_) {
160 if (::dup2(fd, 2) < 0)
165 if (! stderrLog_.empty()) {
166 int fd (::open(stderrLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666));
169 if (::dup2(fd, 2) < 0)
176 (senf::log::CRITICAL)
177 ("log-file reopen failed: (" << errno << ") " << ::strerror(errno)) );
180 prefix_ void senf::Daemon::pidFile(std::string const & f)
186 bool signaled (false);
192 prefix_ void senf::Daemon::detach()
194 if (daemonize_ && ! detached_) {
196 // To ensure all data is written to the console log file in the correct order, we suspend
197 // execution here until the parent process tells us to continue via SIGUSR1: We block
198 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
199 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
200 // SIGUSR1 and reinstall the old signal mask and action.
203 ::sigemptyset(&usrsig);
204 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
205 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
206 struct ::sigaction oldact;
207 struct ::sigaction usract;
208 ::memset(&usract, 0, sizeof(usract));
209 usract.sa_handler = &waitusr;
210 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
211 ::sigset_t waitsig (oldsig);
212 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
214 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
215 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
216 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
217 LIBC_CALL( ::close, (nul) );
221 ::sigsuspend(&waitsig);
223 SENF_THROW_SYSTEM_EXCEPTION("::sigsuspend()");
226 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
227 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
234 /* Purposely *not* derived from std::exception */
235 struct DaemonExitException {
236 DaemonExitException(unsigned c) : code(c) {}
241 prefix_ void senf::Daemon::exit(unsigned code)
243 throw DaemonExitException(code);
246 prefix_ int senf::Daemon::start(int argc, char const ** argv)
258 installSighandlers();
259 if (! pidfile_.empty()) {
261 pidfileCreated_ = true;
263 std::cerr << "PID file '" << pidfile_
264 << "' creation failed. Daemon running ?" << std::endl;
271 catch (DaemonExitException & e) {
277 catch (std::exception & e) {
278 std::cerr << "\n*** Fatal exception: " << e.what() << "\n" << std::endl;
282 std::cerr << "\n*** Fatal exception: (unknown)" << "\n" << std::endl;
291 prefix_ senf::Daemon & senf::Daemon::instance()
293 BOOST_ASSERT( instance_ );
297 ////////////////////////////////////////
300 prefix_ senf::Daemon::Daemon()
301 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
302 pidfileCreated_(false), detached_(false)
304 BOOST_ASSERT( ! instance_ );
308 senf::Daemon * senf::Daemon::instance_ (0);
310 ////////////////////////////////////////
313 prefix_ void senf::Daemon::configure()
315 // int i (not unsigned) since argc_ is int ...
316 for (int i (1); i<argc_; ++i) {
317 std::string argv (argv_[i]);
318 if (argv == "--no-daemon")
320 else if (boost::starts_with(argv, "--console-log=")) {
321 std::string arg (argv.substr(14u));
322 std::string::size_type komma (arg.find(','));
323 if (komma == std::string::npos) {
325 if (arg == std::string("none")) consoleLog("");
326 else if (!arg.empty()) consoleLog(arg);
328 std::string arg1 (arg,0,komma);
329 std::string arg2 (arg,komma+1);
332 if (arg1 == std::string("none")) consoleLog("",StdOut);
333 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
334 if (arg2 == std::string("none")) consoleLog("",StdErr);
335 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
338 else if (boost::starts_with(argv, "--pid-file="))
339 pidFile(std::string(std::string(argv_[i]), 11u));
343 prefix_ void senf::Daemon::main()
350 prefix_ void senf::Daemon::init()
353 prefix_ void senf::Daemon::run()
356 prefix_ void senf::Daemon::fork()
361 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
362 LIBC_CALL( ::dup2, (nul, 0) );
363 LIBC_CALL( ::close, (nul) );
364 LIBC_CALL( ::pipe, (coutpipe) );
365 LIBC_CALL( ::pipe, (cerrpipe) );
367 // We need to block the SIGCHLD signal here so we don't miss it, if the child
371 ::sigemptyset(&cldsig);
372 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
373 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
375 if (! senf::scheduler::empty() ) {
379 "Scheduler not empty before fork(). THIS MUST NOT HAPPEN.\n"
380 "The scheduler will be reinitialized by the fork() and lose all registrations.\n\n";
381 senf::scheduler::detail::EventManager::instance().listEvents(std::cerr);
383 "\n*** WARNING ***\n"
387 LIBC_CALL_RV( pid, ::fork, () );
392 LIBC_CALL( ::dup2, (coutpipe[1],1) );
393 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
394 LIBC_CALL( ::close, (coutpipe[0]) );
395 LIBC_CALL( ::close, (coutpipe[1]) );
396 LIBC_CALL( ::close, (cerrpipe[0]) );
397 LIBC_CALL( ::close, (cerrpipe[1]) );
398 LIBC_CALL( ::setsid, () );
399 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
401 senf::scheduler::restart();
405 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
408 LIBC_CALL( ::close, (coutpipe[1]) );
409 LIBC_CALL( ::close, (cerrpipe[1]) );
411 senf::scheduler::restart();
413 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
419 prefix_ bool senf::Daemon::pidfileCreate()
421 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
422 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
423 // was some race condition, probably over NFS.
425 std::string tempname;
426 boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
429 char hostname[HOST_NAME_MAX+1];
430 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
431 hostname[HOST_NAME_MAX] = 0;
432 std::stringstream tempname_s;
433 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
434 tempname = tempname_s.str();
439 std::ofstream pidf (tempname.c_str());
441 SENF_THROW_SYSTEM_EXCEPTION("")
442 << " Could not open pidfile \"" << tempname << "\" for output.";
443 pidf << ::getpid() << std::endl;
445 SENF_THROW_SYSTEM_EXCEPTION("")
446 << " Could not write to pidfile \"" << tempname << "\".";
449 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
451 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % pidfile_ % tempname;
455 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
456 LIBC_CALL( ::unlink, (tempname.c_str()) );
457 return s.st_nlink == 2;
460 // pidfile exists. Check, whether the pid in the pidfile still exists.
463 std::ifstream pidf (pidfile_.c_str());
464 if ( ! (pidf >> old_pid)
466 || ::kill(old_pid, 0) >= 0
467 || errno == EPERM ) {
468 LIBC_CALL( ::unlink, (tempname.c_str()) );
473 // If we reach this point, the pid file exists but the process mentioned within the
474 // pid file does *not* exists. We assume, the pid file to be stale.
476 // I hope, the following procedure is without race condition: We remove our generated
477 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
478 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
479 // must have already created his hardlink. We then truncate the file and write our pid.
481 LIBC_CALL( ::unlink, (tempname.c_str() ));
482 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
484 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % tempname % pidfile_;
485 // Hmm ... the pidfile mysteriously disappeared ... try again.
491 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
492 if (s.st_nlink != 2) {
493 LIBC_CALL( ::unlink, (tempname.c_str()) );
499 std::ofstream pidf (tempname.c_str());
500 pidf << ::getpid() << std::endl;
503 LIBC_CALL( ::unlink, (tempname.c_str()) );
513 void fatalSignalsHandler(int sig, ::siginfo_t * info, void * arg)
515 // ::ucontext_t * ucontext = static_cast<ucontext_t*>(arg);
516 std::cerr << "\n" << "Signal " << senf::signalName(sig) << '(' << sig << ')'
520 std::cerr << "Invalid memory access at " << info->si_addr << "\n";
522 static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
523 unsigned nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
525 // Hack the callers address into the backtrace
526 // entries[1] = reinterpret_cast<void *>(ucontext->uc_mcontext.gregs[REG_EIP]);
528 std::cerr << "Backtrace:\n";
529 senf::formatBacktrace(std::cerr, entries, nEntries);
530 std::cerr << "-- \n";
532 if (sig != SIGUSR2) {
533 ::signal(sig, SIG_DFL);
534 ::kill(::getpid(), sig);
543 void sighupHandler(int sig)
545 senf::Daemon::instance().logReopen();
549 prefix_ void senf::Daemon::installSighandlers()
551 struct ::sigaction sa;
553 ::sigemptyset(&sa.sa_mask);
554 sa.sa_handler = &sighupHandler;
555 sa.sa_flags = SA_RESTART;
557 ::sigaction(SIGHUP, &sa, NULL);
559 sa.sa_handler = SIG_IGN;
560 ::sigaction(SIGPIPE, &sa, NULL);
563 sa.sa_sigaction = &fatalSignalsHandler;
564 sa.sa_flags = SA_RESTART | SA_SIGINFO;
566 ::sigaction(SIGILL, &sa, NULL);
567 ::sigaction(SIGTRAP, &sa, NULL);
568 ::sigaction(SIGABRT, &sa, NULL);
569 ::sigaction(SIGFPE, &sa, NULL);
570 ::sigaction(SIGBUS, &sa, NULL);
571 ::sigaction(SIGSEGV, &sa, NULL);
572 ::sigaction(SIGSTKFLT, &sa, NULL);
573 ::sigaction(SIGSYS, &sa, NULL);
574 ::sigaction(SIGUSR2, &sa, NULL);
578 ///////////////////////////////////////////////////////////////////////////
579 // senf::detail::DaemonWatcher
581 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
582 int stdout, int stderr)
583 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
584 stderr_(stderr), sigChld_(false),
585 cldSignal_ (SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this)),
586 timer_ ("senf::detail::DaemonWatcher::childOk", senf::membind(&DaemonWatcher::childOk, this)),
587 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
588 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
590 coutForwarder_.addTarget(1);
592 coutForwarder_.addTarget(stdout_);
593 cerrForwarder_.addTarget(2);
595 cerrForwarder_.addTarget(stderr_);
598 prefix_ void senf::detail::DaemonWatcher::run()
600 scheduler::process();
603 ////////////////////////////////////////
606 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
609 case 1 : coutpipe_ = -1; break;
610 case 2 : cerrpipe_ = -1; break;
613 if (coutpipe_ == -1 && cerrpipe_ == -1) {
615 childDied(); // does not return
616 if (::kill(childPid_, SIGUSR1) < 0 && errno != ESRCH)
617 SENF_THROW_SYSTEM_EXCEPTION("::kill()");
618 timer_.timeout(scheduler::eventTime() + ClockService::seconds(1));
622 prefix_ void senf::detail::DaemonWatcher::sigChld(siginfo_t const &)
625 if (coutpipe_ == -1 && cerrpipe_ == -1)
626 childDied(); // does not return
629 prefix_ void senf::detail::DaemonWatcher::childDied()
632 if (::waitpid(childPid_,&status,0) < 0) SENF_THROW_SYSTEM_EXCEPTION("::waitpid()");
633 if (WIFSIGNALED(status)) {
634 ::signal(WTERMSIG(status),SIG_DFL);
635 ::kill(::getpid(), WTERMSIG(status));
636 // should not be reached
639 if (WEXITSTATUS(status) == 0)
641 ::_exit(WEXITSTATUS(status));
644 prefix_ void senf::detail::DaemonWatcher::childOk()
646 scheduler::terminate();
649 ///////////////////////////////////////////////////////////////////////////
650 // senf::detail::DaemonWatcher::Forwarder
652 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
653 : src_(src), cb_(cb),
654 readevent_("senf::detail::DaemonWatcher::Forwarder::readevent", senf::membind(&Forwarder::readData, this),
655 src_, scheduler::FdEvent::EV_READ)
658 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
660 targets_.clear_and_destroy(DestroyDelete());
663 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
665 targets_.push_back(*(new Target(*this, fd)));
668 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(int event)
674 n = ::read(src_,buf,1024);
677 SENF_THROW_SYSTEM_EXCEPTION("::read()");
687 readevent_.disable();
691 if (targets_.empty())
694 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
695 if (i->offset >= buffer_.size())
696 i->writeevent.enable();
698 buffer_.insert(buffer_.end(), buf, buf+n);
701 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(int event, Target * target)
703 if (event != scheduler::FdEvent::EV_WRITE) {
704 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
705 targets_.erase_and_destroy(Targets::current(*target),DestroyDelete());
706 if (targets_.empty() && src_ == -1)
712 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
713 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
715 int w (::write(target->fd, buf, n));
717 if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::write()");
722 n = std::min_element(
723 targets_.begin(), targets_.end(),
724 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
726 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
728 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
731 if (target->offset >= buffer_.size())
732 target->writeevent.disable();
733 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
740 ///////////////////////////////cc.e////////////////////////////////////////
742 //#include "Daemon.mpp"
748 // comment-column: 40
749 // c-file-style: "senf"
750 // indent-tabs-mode: nil
751 // ispell-local-dictionary: "american"
752 // compile-command: "scons -u test"