4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer NETwork research (NET)
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 "../Utils/Exception.hh"
42 #include "../Utils/membind.hh"
44 //#include "Daemon.mpp"
46 ///////////////////////////////cc.p////////////////////////////////////////
48 #define LIBC_CALL(fn, args) if (fn args < 0) throwErrno(#fn "()")
49 #define LIBC_CALL_RV(var, fn, args) int var (fn args); if (var < 0) throwErrno(#fn "()")
51 ///////////////////////////////////////////////////////////////////////////
54 prefix_ senf::Daemon::~Daemon()
56 if (! pidfile_.empty())
57 LIBC_CALL( ::unlink, (pidfile_.c_str()) );
60 prefix_ void senf::Daemon::daemonize(bool v)
65 prefix_ bool senf::Daemon::daemon()
70 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
73 case StdOut : stdoutLog_ = path; break;
74 case StdErr : stderrLog_ = path; break;
75 case Both : stdoutLog_ = path; stderrLog_ = path; break;
80 prefix_ void senf::Daemon::openLog()
83 if (! stdoutLog_.empty()) {
84 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
86 throwErrno("::open()");
89 if (stderrLog_ == stdoutLog_)
91 else if (! stderrLog_.empty()) {
92 fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
94 throwErrno("::open()");
99 prefix_ void senf::Daemon::pidFile(std::string const & f)
105 bool signaled (false);
111 prefix_ void senf::Daemon::detach()
115 // To ensure all data is written to the console log file in the correct order, we suspend
116 // execution here until the parent process tells us to continue via SIGUSR1: We block
117 // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
118 // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
119 // SIGUSR1 and reinstall the old signal mask and action.
122 ::sigemptyset(&usrsig);
123 LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
124 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
125 struct ::sigaction oldact;
126 struct ::sigaction usract;
127 ::memset(&usract, 0, sizeof(usract));
128 usract.sa_handler = &waitusr;
129 LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
130 ::sigset_t waitsig (oldsig);
131 LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
133 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
134 LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
135 LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
136 LIBC_CALL( ::close, (nul) );
140 ::sigsuspend(&waitsig);
142 throwErrno("::sigsuspend()");
145 LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
146 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
150 prefix_ int senf::Daemon::start(int argc, char const ** argv)
167 if (! pidfile_.empty() && ! pidfileCreate()) {
168 std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?"
178 catch (std::exception & e) {
179 std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
183 std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
192 ////////////////////////////////////////
195 prefix_ senf::Daemon::Daemon()
196 : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
200 ////////////////////////////////////////
203 prefix_ void senf::Daemon::configure()
205 for (int i (1); i<argc_; ++i) {
206 if (argv_[i] == std::string("--no-daemon"))
208 else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
209 std::string arg (std::string(argv_[i]), 14u);
210 std::string::size_type komma (arg.find(','));
211 if (komma == std::string::npos) {
215 std::string arg1 (arg,0,komma);
216 std::string arg2 (arg,komma+1);
219 if (arg1 == std::string("none")) consoleLog("",StdOut);
220 else if (! arg1.empty() ) consoleLog(arg1, StdOut);
221 if (arg2 == std::string("none")) consoleLog("",StdErr);
222 else if (! arg2.empty() ) consoleLog(arg2, StdErr);
225 else if (boost::starts_with(argv_[i], std::string("--pid-file=")))
226 pidFile(std::string(std::string(argv_[i]), 11u));
230 prefix_ void senf::Daemon::main()
237 prefix_ void senf::Daemon::init()
240 prefix_ void senf::Daemon::run()
243 prefix_ void senf::Daemon::fork()
248 LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
249 LIBC_CALL( ::dup2, (nul, 0) );
250 LIBC_CALL( ::close, (nul) );
251 LIBC_CALL( ::pipe, (coutpipe) );
252 LIBC_CALL( ::pipe, (cerrpipe) );
254 // We need to block the SIGCHLD signal here so we don't miss it, if the child
258 ::sigemptyset(&cldsig);
259 LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
260 LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
262 LIBC_CALL_RV( pid, ::fork, () );
267 LIBC_CALL( ::dup2, (coutpipe[1],1) );
268 LIBC_CALL( ::dup2, (cerrpipe[1],2) );
269 LIBC_CALL( ::close, (coutpipe[0]) );
270 LIBC_CALL( ::close, (coutpipe[1]) );
271 LIBC_CALL( ::close, (cerrpipe[0]) );
272 LIBC_CALL( ::close, (cerrpipe[1]) );
273 LIBC_CALL( ::setsid, () );
274 LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
278 // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
281 LIBC_CALL( ::close, (coutpipe[1]) );
282 LIBC_CALL( ::close, (cerrpipe[1]) );
284 detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
290 prefix_ bool senf::Daemon::pidfileCreate()
292 // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
293 // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
294 // was some race condition, probably over NFS.
296 std::string tempname;
299 char hostname[HOST_NAME_MAX+1];
300 LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
301 hostname[HOST_NAME_MAX] = 0;
302 std::stringstream tempname_s;
303 tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
304 tempname = tempname_s.str();
309 std::ofstream pidf (tempname.c_str());
310 pidf << ::getpid() << std::endl;
313 if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
315 throwErrno("::link()");
319 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
320 LIBC_CALL( ::unlink, (tempname.c_str()) );
321 return s.st_nlink == 2;
324 // pidfile exists. Check, whether the pid in the pidfile still exists.
327 std::ifstream pidf (pidfile_.c_str());
328 if ( ! (pidf >> old_pid)
330 || ::kill(old_pid, 0) >= 0
335 // If we reach this point, the pid file exists but the process mentioned within the
336 // pid file does *not* exists. We assume, the pid file to be stale.
338 // I hope, the following procedure is without race condition: We remove our generated
339 // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
340 // the hard-link count of this file is 2. If it is not, we terminate, since someone else
341 // must have already created his hardlink. We then truncate the file and write our pid.
343 LIBC_CALL( ::unlink, (tempname.c_str() ));
344 if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
345 if (errno != ENOENT) throwErrno("::link()");
346 // Hmm ... the pidfile mysteriously disappeared ... try again.
352 LIBC_CALL( ::stat, (tempname.c_str(), &s) );
353 if (s.st_nlink != 2) {
354 LIBC_CALL( ::unlink, (tempname.c_str()) );
360 std::ofstream pidf (tempname.c_str());
361 pidf << ::getpid() << std::endl;
364 LIBC_CALL( ::unlink, (tempname.c_str()) );
370 ///////////////////////////////////////////////////////////////////////////
371 // senf::detail::DaemonWatcher
373 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
374 int stdout, int stderr)
375 : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
376 stderr_(stderr), sigChld_(false),
377 coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)),
378 cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2))
380 coutForwarder_.addTarget(1);
382 coutForwarder_.addTarget(stdout_);
383 cerrForwarder_.addTarget(2);
385 cerrForwarder_.addTarget(stderr_);
388 prefix_ void senf::detail::DaemonWatcher::run()
390 Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
391 Scheduler::instance().process();
394 ////////////////////////////////////////
397 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
400 case 1 : coutpipe_ = -1; break;
401 case 2 : cerrpipe_ = -1; break;
404 if (coutpipe_ == -1 && cerrpipe_ == -1) {
406 childDied(); // does not return
407 if (::kill(childPid_, SIGUSR1) < 0)
408 if (errno != ESRCH) throwErrno("::kill()");
409 Scheduler::instance().timeout(
410 Scheduler::instance().eventTime() + ClockService::seconds(1),
411 senf::membind(&DaemonWatcher::childOk, this));
415 prefix_ void senf::detail::DaemonWatcher::sigChld()
418 if (coutpipe_ == -1 && cerrpipe_ == -1)
419 childDied(); // does not return
422 prefix_ void senf::detail::DaemonWatcher::childDied()
425 if (::waitpid(childPid_,&status,0) < 0) throwErrno("::waitpid()");
426 if (WIFSIGNALED(status)) {
427 ::signal(WTERMSIG(status),SIG_DFL);
428 ::kill(::getpid(), WTERMSIG(status));
429 // should not be reached
432 if (WEXITSTATUS(status) == 0)
434 ::_exit(WEXITSTATUS(status));
437 prefix_ void senf::detail::DaemonWatcher::childOk()
439 Scheduler::instance().terminate();
442 ///////////////////////////////////////////////////////////////////////////
443 // senf::detail::DaemonWatcher::Forwarder
445 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
448 Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
452 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
455 Scheduler::instance().remove(src_);
457 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
458 if (i->offset >= buffer_.size())
459 Scheduler::instance().remove(i->fd);
462 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
464 Target target = { fd, 0 };
465 targets_.push_back(target);
468 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
474 n = ::read(src_,buf,1024);
476 if (errno != EINTR) throwErrno("::read()");
483 Scheduler::instance().remove(src_);
490 if (targets_.empty())
493 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
494 if (i->offset >= buffer_.size())
495 Scheduler::instance().add( i->fd,
496 boost::bind(&Forwarder::writeData, this, _1, i),
497 Scheduler::EV_WRITE );
499 buffer_.insert(buffer_.end(), buf, buf+n);
502 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
503 Targets::iterator target)
505 if (event != Scheduler::EV_WRITE) {
506 // Broken pipe while writing data ? Not much, we can do here, we just drop the data
507 Scheduler::instance().remove(target->fd);
508 targets_.erase(target);
509 if (targets_.empty() && src_ == -1)
515 int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
516 std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
518 int w (::write(target->fd, buf, n));
520 if (errno != EINTR) throwErrno("::write()");
525 n = std::min_element(
526 targets_.begin(), targets_.end(),
527 boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
529 buffer_.erase(buffer_.begin(), buffer_.begin()+n);
531 for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
534 if (target->offset >= buffer_.size())
535 Scheduler::instance().remove(target->fd);
536 if (src_ == -1 && (buffer_.empty() || targets_.empty()))
543 ///////////////////////////////cc.e////////////////////////////////////////
545 //#include "Daemon.mpp"
551 // comment-column: 40
552 // c-file-style: "senf"
553 // indent-tabs-mode: nil
554 // ispell-local-dictionary: "american"
555 // compile-command: "scons -u test"