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) \
50 SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
52 #define LIBC_CALL_RV(var, fn, args) \
53 int var (fn args); if (var < 0) SENF_THROW_SYSTEM_EXCEPTION(#fn "()")
55 ///////////////////////////////////////////////////////////////////////////
58 prefix_ senf::Daemon::~Daemon()
60 if (pidfileCreated_) {
62 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
63 } catch (Exception e) {
64 // e << "; could not unlink " << pidfile_.c_str();
70 prefix_ void senf::Daemon::daemonize(bool v)
75 prefix_ bool senf::Daemon::daemon()
80 prefix_ int senf::Daemon::argc()
85 prefix_ char ** senf::Daemon::argv()
90 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
93 case StdOut : stdoutLog_ = path; break;
94 case StdErr : stderrLog_ = path; break;
95 case Both : stdoutLog_ = path; stderrLog_ = path; break;
100 prefix_ void senf::Daemon::openLog()
103 if (! stdoutLog_.empty()) {
104 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
106 SENF_THROW_SYSTEM_EXCEPTION("")
107 << " Could not open \"" << stdoutLog_ << "\" for redirecting stdout.";
110 if (stderrLog_ == stdoutLog_)
112 else if (! stderrLog_.empty()) {
113 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
115 SENF_THROW_SYSTEM_EXCEPTION("")
116 << " Could not open \"" << stderrLog_ << "\" for redirecting stderr.";
121 prefix_ void senf::Daemon::pidFile(std::string const & f)
127 bool signaled (false);
133 prefix_ void senf::Daemon::detach()
135 if (daemonize_ && ! detached_) {
137 // To ensure all data is written to the console log file in the correct order, we suspend
138 // execution here until the parent process tells us to continue via SIGUSR1: We block
139 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
140 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
141 // SIGUSR1 and reinstall the old signal mask and action.
144 ::sigemptyset(&usrsig);
145 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
146 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
147 struct ::sigaction oldact;
148 struct ::sigaction usract;
149 ::memset(&usract, 0, sizeof(usract));
150 usract.sa_handler = &waitusr;
151 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
152 ::sigset_t waitsig (oldsig);
153 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
155 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
156 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
157 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
158 LIBC_CALL( ::close, (nul) );
162 ::sigsuspend(&waitsig);
164 SENF_THROW_SYSTEM_EXCEPTION("::sigsuspend()");
167 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
168 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
175 /* Purposely *not* derived from std::exception */
176 struct DaemonExitException {
177 DaemonExitException(unsigned c) : code(c) {}
182 prefix_ void senf::Daemon::exit(unsigned code)
184 throw DaemonExitException(code);
187 prefix_ int senf::Daemon::start(int argc, char ** argv)
199 if (! pidfile_.empty()) {
201 pidfileCreated_ = true;
203 std::cerr << "PID file '" << pidfile_
204 << "' creation failed. Daemon running ?" << std::endl;
211 catch (DaemonExitException & e) {
217 catch (std::exception & e) {
218 std::cerr << "\n*** Fatal exception: " << e.what() << "\n" << std::endl;
222 std::cerr << "\n*** Fatal exception: (unknown)" << "\n" << std::endl;
231 ////////////////////////////////////////
234 prefix_ senf::Daemon::Daemon()
235 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
236 pidfileCreated_(false), detached_(false)
239 ////////////////////////////////////////
242 prefix_ void senf::Daemon::configure()
244 for (int i (1); i<argc_; ++i) {
245 if (argv_[i] == std::string("--no-daemon"))
247 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
248 std::string arg (std::string(argv_[i]), 14u);
249 std::string::size_type komma (arg.find(','));
250 if (komma == std::string::npos) {
252 if (arg == std::string("none")) consoleLog("");
253 else if (!arg.empty()) consoleLog(arg);
255 std::string arg1 (arg,0,komma);
256 std::string arg2 (arg,komma+1);
259 if (arg1 == std::string("none")) consoleLog("",StdOut);
260 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
261 if (arg2 == std::string("none")) consoleLog("",StdErr);
262 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
265 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
266 pidFile(std::string(std::string(argv_[i]), 11u));
270 prefix_ void senf::Daemon::main()
277 prefix_ void senf::Daemon::init()
280 prefix_ void senf::Daemon::run()
283 prefix_ void senf::Daemon::fork()
288 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
289 LIBC_CALL( ::dup2, (nul, 0) );
290 LIBC_CALL( ::close, (nul) );
291 LIBC_CALL( ::pipe, (coutpipe) );
292 LIBC_CALL( ::pipe, (cerrpipe) );
294 // We need to block the SIGCHLD signal here so we don't miss it, if the child
298 ::sigemptyset(&cldsig);
299 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
300 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
302 LIBC_CALL_RV( pid, ::fork, () );
307 LIBC_CALL( ::dup2, (coutpipe[1],1) );
308 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
309 LIBC_CALL( ::close, (coutpipe[0]) );
310 LIBC_CALL( ::close, (coutpipe[1]) );
311 LIBC_CALL( ::close, (cerrpipe[0]) );
312 LIBC_CALL( ::close, (cerrpipe[1]) );
313 LIBC_CALL( ::setsid, () );
314 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
318 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
321 LIBC_CALL( ::close, (coutpipe[1]) );
322 LIBC_CALL( ::close, (cerrpipe[1]) );
324 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
330 prefix_ bool senf::Daemon::pidfileCreate()
332 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
333 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
334 // was some race condition, probably over NFS.
336 std::string tempname;
337 boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
340 char hostname[HOST_NAME_MAX+1];
341 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
342 hostname[HOST_NAME_MAX] = 0;
343 std::stringstream tempname_s;
344 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
345 tempname = tempname_s.str();
350 std::ofstream pidf (tempname.c_str());
352 SENF_THROW_SYSTEM_EXCEPTION("")
353 << " Could not open pidfile \"" << tempname << "\" for output.";
354 pidf << ::getpid() << std::endl;
356 SENF_THROW_SYSTEM_EXCEPTION("")
357 << " Could not write to pidfile \"" << tempname << "\".";
360 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
362 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % pidfile_ % tempname;
366 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
367 LIBC_CALL( ::unlink, (tempname.c_str()) );
368 return s.st_nlink == 2;
371 // pidfile exists. Check, whether the pid in the pidfile still exists.
374 std::ifstream pidf (pidfile_.c_str());
375 if ( ! (pidf >> old_pid)
377 || ::kill(old_pid, 0) >= 0
378 || errno == EPERM ) {
379 LIBC_CALL( ::unlink, (tempname.c_str()) );
384 // If we reach this point, the pid file exists but the process mentioned within the
385 // pid file does *not* exists. We assume, the pid file to be stale.
387 // I hope, the following procedure is without race condition: We remove our generated
388 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
389 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
390 // must have already created his hardlink. We then truncate the file and write our pid.
392 LIBC_CALL( ::unlink, (tempname.c_str() ));
393 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
395 SENF_THROW_SYSTEM_EXCEPTION("") << linkErrorFormat % tempname % pidfile_;
396 // Hmm ... the pidfile mysteriously disappeared ... try again.
402 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
403 if (s.st_nlink != 2) {
404 LIBC_CALL( ::unlink, (tempname.c_str()) );
410 std::ofstream pidf (tempname.c_str());
411 pidf << ::getpid() << std::endl;
414 LIBC_CALL( ::unlink, (tempname.c_str()) );
420 ///////////////////////////////////////////////////////////////////////////
421 // senf::detail::DaemonWatcher
423 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
424 int stdout, int stderr)
425 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
426 stderr_(stderr), sigChld_(false),
427 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
428 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
430 coutForwarder_.addTarget(1);
432 coutForwarder_.addTarget(stdout_);
433 cerrForwarder_.addTarget(2);
435 cerrForwarder_.addTarget(stderr_);
438 prefix_ void senf::detail::DaemonWatcher::run()
440 Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
441 Scheduler::instance().process();
444 ////////////////////////////////////////
447 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
450 case 1 : coutpipe_ = -1; break;
451 case 2 : cerrpipe_ = -1; break;
454 if (coutpipe_ == -1 && cerrpipe_ == -1) {
456 childDied(); // does not return
457 if (::kill(childPid_, SIGUSR1) < 0)
458 if (errno != ESRCH) SENF_THROW_SYSTEM_EXCEPTION("::kill()");
459 Scheduler::instance().timeout(
460 Scheduler::instance().eventTime() + ClockService::seconds(1),
461 senf::membind(&DaemonWatcher::childOk, this));
465 prefix_ void senf::detail::DaemonWatcher::sigChld()
468 if (coutpipe_ == -1 && cerrpipe_ == -1)
469 childDied(); // does not return
472 prefix_ void senf::detail::DaemonWatcher::childDied()
475 if (::waitpid(childPid_,&status,0) < 0) SENF_THROW_SYSTEM_EXCEPTION("::waitpid()");
476 if (WIFSIGNALED(status)) {
477 ::signal(WTERMSIG(status),SIG_DFL);
478 ::kill(::getpid(), WTERMSIG(status));
479 // should not be reached
482 if (WEXITSTATUS(status) == 0)
484 ::_exit(WEXITSTATUS(status));
487 prefix_ void senf::detail::DaemonWatcher::childOk()
489 Scheduler::instance().terminate();
492 ///////////////////////////////////////////////////////////////////////////
493 // senf::detail::DaemonWatcher::Forwarder
495 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
498 Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
502 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
505 Scheduler::instance().remove(src_);
507 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
508 if (i->offset >= buffer_.size())
509 Scheduler::instance().remove(i->fd);
512 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
514 Target target = { fd, 0 };
515 targets_.push_back(target);
518 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
524 n = ::read(src_,buf,1024);
526 if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::read()");
533 Scheduler::instance().remove(src_);
540 if (targets_.empty())
543 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
544 if (i->offset >= buffer_.size())
545 Scheduler::instance().add( i->fd,
546 boost::bind(&Forwarder::writeData, this, _1, i),
547 Scheduler::EV_WRITE );
549 buffer_.insert(buffer_.end(), buf, buf+n);
552 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
553 Targets::iterator target)
555 if (event != Scheduler::EV_WRITE) {
556 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
557 Scheduler::instance().remove(target->fd);
558 targets_.erase(target);
559 if (targets_.empty() && src_ == -1)
565 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
566 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
568 int w (::write(target->fd, buf, n));
570 if (errno != EINTR) SENF_THROW_SYSTEM_EXCEPTION("::write()");
575 n = std::min_element(
576 targets_.begin(), targets_.end(),
577 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
579 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
581 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
584 if (target->offset >= buffer_.size())
585 Scheduler::instance().remove(target->fd);
586 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
593 ///////////////////////////////cc.e////////////////////////////////////////
595 //#include "Daemon.mpp"
601 // comment-column: 40
602 // c-file-style: "senf"
603 // indent-tabs-mode: nil
604 // ispell-local-dictionary: "american"
605 // compile-command: "scons -u test"