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>
39 #include <boost/algorithm/string/predicate.hpp>
40 #include <boost/algorithm/string/trim.hpp>
41 #include <boost/format.hpp>
42 #include "../Exception.hh"
43 #include "../membind.hh"
45 //#include "Daemon.mpp"
47 ///////////////////////////////cc.p////////////////////////////////////////
49 #define LIBC_CALL(fn, args) if (fn args < 0) throw SystemException(#fn "()")
50 #define LIBC_CALL_RV(var, fn, args) int var (fn args); if (var < 0) throw SystemException(#fn "()")
52 ///////////////////////////////////////////////////////////////////////////
55 prefix_ senf::Daemon::~Daemon()
57 if (! pidfile_.empty()) {
59 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
60 } catch (Exception e) {
61 // e << "; could not unlink " << pidfile_.c_str();
67 prefix_ void senf::Daemon::daemonize(bool v)
72 prefix_ bool senf::Daemon::daemon()
77 prefix_ int senf::Daemon::argc() {
81 prefix_ char const ** senf::Daemon::argv() {
85 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
88 case StdOut : stdoutLog_ = path; break;
89 case StdErr : stderrLog_ = path; break;
90 case Both : stdoutLog_ = path; stderrLog_ = path; break;
95 prefix_ void senf::Daemon::openLog()
98 if (! stdoutLog_.empty()) {
99 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
101 throw SystemException()
102 << " Could not open \"" << stdoutLog_ << "\" for redirecting stdout.";
105 if (stderrLog_ == stdoutLog_)
107 else if (! stderrLog_.empty()) {
108 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
110 throw SystemException()
111 << " Could not open \"" << stderrLog_ << "\" for redirecting stderr.";
116 prefix_ void senf::Daemon::pidFile(std::string const & f)
122 bool signaled (false);
128 prefix_ void senf::Daemon::detach()
130 if (daemonize_ && ! detached_) {
132 // To ensure all data is written to the console log file in the correct order, we suspend
133 // execution here until the parent process tells us to continue via SIGUSR1: We block
134 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
135 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
136 // SIGUSR1 and reinstall the old signal mask and action.
139 ::sigemptyset(&usrsig);
140 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
141 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
142 struct ::sigaction oldact;
143 struct ::sigaction usract;
144 ::memset(&usract, 0, sizeof(usract));
145 usract.sa_handler = &waitusr;
146 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
147 ::sigset_t waitsig (oldsig);
148 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
150 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
151 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
152 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
153 LIBC_CALL( ::close, (nul) );
157 ::sigsuspend(&waitsig);
159 throw SystemException("::sigsuspend()");
162 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
163 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
170 /* Purposely *not* derived from std::exception */
171 struct DaemonExitException {
172 DaemonExitException(unsigned c) : code(c) {}
177 prefix_ void senf::Daemon::exit(unsigned code)
179 throw DaemonExitException(code);
182 prefix_ int senf::Daemon::start(int argc, char const ** argv)
194 if (! pidfile_.empty() && ! pidfileCreate()) {
195 std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?"
202 catch (DaemonExitException & e) {
208 catch (std::exception & e) {
209 std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
213 std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
222 ////////////////////////////////////////
225 prefix_ senf::Daemon::Daemon()
226 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
230 ////////////////////////////////////////
233 prefix_ void senf::Daemon::configure()
235 for (int i (1); i<argc_; ++i) {
236 if (argv_[i] == std::string("--no-daemon"))
238 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
239 std::string arg (std::string(argv_[i]), 14u);
240 std::string::size_type komma (arg.find(','));
241 if (komma == std::string::npos) {
243 if (arg == std::string("none")) consoleLog("");
244 else if (!arg.empty()) consoleLog(arg);
246 std::string arg1 (arg,0,komma);
247 std::string arg2 (arg,komma+1);
250 if (arg1 == std::string("none")) consoleLog("",StdOut);
251 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
252 if (arg2 == std::string("none")) consoleLog("",StdErr);
253 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
256 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
257 pidFile(std::string(std::string(argv_[i]), 11u));
261 prefix_ void senf::Daemon::main()
268 prefix_ void senf::Daemon::init()
271 prefix_ void senf::Daemon::run()
274 prefix_ void senf::Daemon::fork()
279 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
280 LIBC_CALL( ::dup2, (nul, 0) );
281 LIBC_CALL( ::close, (nul) );
282 LIBC_CALL( ::pipe, (coutpipe) );
283 LIBC_CALL( ::pipe, (cerrpipe) );
285 // We need to block the SIGCHLD signal here so we don't miss it, if the child
289 ::sigemptyset(&cldsig);
290 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
291 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
293 LIBC_CALL_RV( pid, ::fork, () );
298 LIBC_CALL( ::dup2, (coutpipe[1],1) );
299 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
300 LIBC_CALL( ::close, (coutpipe[0]) );
301 LIBC_CALL( ::close, (coutpipe[1]) );
302 LIBC_CALL( ::close, (cerrpipe[0]) );
303 LIBC_CALL( ::close, (cerrpipe[1]) );
304 LIBC_CALL( ::setsid, () );
305 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
309 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
312 LIBC_CALL( ::close, (coutpipe[1]) );
313 LIBC_CALL( ::close, (cerrpipe[1]) );
315 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
321 prefix_ bool senf::Daemon::pidfileCreate()
323 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
324 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
325 // was some race condition, probably over NFS.
327 std::string tempname;
328 boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
331 char hostname[HOST_NAME_MAX+1];
332 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
333 hostname[HOST_NAME_MAX] = 0;
334 std::stringstream tempname_s;
335 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
336 tempname = tempname_s.str();
341 std::ofstream pidf (tempname.c_str());
343 throw SystemException()
344 << " Could not open pidfile \"" << tempname << "\" for output.";
345 pidf << ::getpid() << std::endl;
347 throw SystemException()
348 << " Could not write to pidfile \"" << tempname << "\".";
351 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
353 throw SystemException() << linkErrorFormat % pidfile_ % tempname;
357 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
358 LIBC_CALL( ::unlink, (tempname.c_str()) );
359 return s.st_nlink == 2;
362 // pidfile exists. Check, whether the pid in the pidfile still exists.
365 std::ifstream pidf (pidfile_.c_str());
366 if ( ! (pidf >> old_pid)
368 || ::kill(old_pid, 0) >= 0
373 // If we reach this point, the pid file exists but the process mentioned within the
374 // pid file does *not* exists. We assume, the pid file to be stale.
376 // I hope, the following procedure is without race condition: We remove our generated
377 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
378 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
379 // must have already created his hardlink. We then truncate the file and write our pid.
381 LIBC_CALL( ::unlink, (tempname.c_str() ));
382 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
384 throw SystemException() << linkErrorFormat % tempname % pidfile_;
385 // Hmm ... the pidfile mysteriously disappeared ... try again.
391 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
392 if (s.st_nlink != 2) {
393 LIBC_CALL( ::unlink, (tempname.c_str()) );
399 std::ofstream pidf (tempname.c_str());
400 pidf << ::getpid() << std::endl;
403 LIBC_CALL( ::unlink, (tempname.c_str()) );
409 ///////////////////////////////////////////////////////////////////////////
410 // senf::detail::DaemonWatcher
412 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
413 int stdout, int stderr)
414 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
415 stderr_(stderr), sigChld_(false),
416 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
417 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
419 coutForwarder_.addTarget(1);
421 coutForwarder_.addTarget(stdout_);
422 cerrForwarder_.addTarget(2);
424 cerrForwarder_.addTarget(stderr_);
427 prefix_ void senf::detail::DaemonWatcher::run()
429 Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
430 Scheduler::instance().process();
433 ////////////////////////////////////////
436 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
439 case 1 : coutpipe_ = -1; break;
440 case 2 : cerrpipe_ = -1; break;
443 if (coutpipe_ == -1 && cerrpipe_ == -1) {
445 childDied(); // does not return
446 if (::kill(childPid_, SIGUSR1) < 0)
447 if (errno != ESRCH) throw SystemException("::kill()");
448 Scheduler::instance().timeout(
449 Scheduler::instance().eventTime() + ClockService::seconds(1),
450 senf::membind(&DaemonWatcher::childOk, this));
454 prefix_ void senf::detail::DaemonWatcher::sigChld()
457 if (coutpipe_ == -1 && cerrpipe_ == -1)
458 childDied(); // does not return
461 prefix_ void senf::detail::DaemonWatcher::childDied()
464 if (::waitpid(childPid_,&status,0) < 0) throw SystemException("::waitpid()");
465 if (WIFSIGNALED(status)) {
466 ::signal(WTERMSIG(status),SIG_DFL);
467 ::kill(::getpid(), WTERMSIG(status));
468 // should not be reached
471 if (WEXITSTATUS(status) == 0)
473 ::_exit(WEXITSTATUS(status));
476 prefix_ void senf::detail::DaemonWatcher::childOk()
478 Scheduler::instance().terminate();
481 ///////////////////////////////////////////////////////////////////////////
482 // senf::detail::DaemonWatcher::Forwarder
484 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
487 Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
491 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
494 Scheduler::instance().remove(src_);
496 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
497 if (i->offset >= buffer_.size())
498 Scheduler::instance().remove(i->fd);
501 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
503 Target target = { fd, 0 };
504 targets_.push_back(target);
507 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
513 n = ::read(src_,buf,1024);
515 if (errno != EINTR) throw SystemException("::read()");
522 Scheduler::instance().remove(src_);
529 if (targets_.empty())
532 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
533 if (i->offset >= buffer_.size())
534 Scheduler::instance().add( i->fd,
535 boost::bind(&Forwarder::writeData, this, _1, i),
536 Scheduler::EV_WRITE );
538 buffer_.insert(buffer_.end(), buf, buf+n);
541 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
542 Targets::iterator target)
544 if (event != Scheduler::EV_WRITE) {
545 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
546 Scheduler::instance().remove(target->fd);
547 targets_.erase(target);
548 if (targets_.empty() && src_ == -1)
554 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
555 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
557 int w (::write(target->fd, buf, n));
559 if (errno != EINTR) throw SystemException("::write()");
564 n = std::min_element(
565 targets_.begin(), targets_.end(),
566 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
568 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
570 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
573 if (target->offset >= buffer_.size())
574 Scheduler::instance().remove(target->fd);
575 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
582 ///////////////////////////////cc.e////////////////////////////////////////
584 //#include "Daemon.mpp"
590 // comment-column: 40
591 // c-file-style: "senf"
592 // indent-tabs-mode: nil
593 // ispell-local-dictionary: "american"
594 // compile-command: "scons -u test"