No longer throw an exception on deleting the pidFile
[senf.git] / Utils / Daemon / Daemon.cc
1 // $Id$
2 //
3 // Copyright (C) 2007
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
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.
12 //
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.
17 //
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.
22
23 /** \file
24     \brief Daemon non-inline non-template implementation */
25
26 #include "Daemon.hh"
27 #include "Daemon.ih"
28
29 // Custom includes
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <unistd.h>
34 #include <fcntl.h>
35 #include <errno.h>
36 #include <signal.h>
37 #include <sstream>
38 #include <algorithm>
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"
44
45 //#include "Daemon.mpp"
46 #define prefix_
47 ///////////////////////////////cc.p////////////////////////////////////////
48
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 "()")
51
52 ///////////////////////////////////////////////////////////////////////////
53 // senf::Daemon
54
55 prefix_ senf::Daemon::~Daemon()
56 {
57     if (! pidfile_.empty()) {
58         try {
59             LIBC_CALL( ::unlink, (pidfile_.c_str()) );
60         } catch (SystemException e) {
61             e << "; could not unlink " << pidfile_.c_str();
62             // throw;
63         }
64     }
65 }
66
67 prefix_ void senf::Daemon::daemonize(bool v)
68 {
69     daemonize_ = v;
70 }
71
72 prefix_ bool senf::Daemon::daemon()
73 {
74     return daemonize_;
75 }
76
77 prefix_ int senf::Daemon::argc() {
78     return argc_;
79 }
80
81 prefix_ char const ** senf::Daemon::argv() {
82     return argv_;
83 }
84
85 prefix_ void senf::Daemon::consoleLog(std::string const & path, StdStream which)
86 {
87     switch (which) {
88     case StdOut : stdoutLog_ = path; break;
89     case StdErr : stderrLog_ = path; break;
90     case Both : stdoutLog_ = path; stderrLog_ = path; break;
91     }
92 }
93
94
95 prefix_ void senf::Daemon::openLog()
96 {
97     int fd (-1);
98     if (! stdoutLog_.empty()) {
99         fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
100         if (fd < 0)
101             throw SystemException("::open()");
102         stdout_ = fd;
103     }
104     if (stderrLog_ == stdoutLog_)
105         stderr_ = fd;
106     else if (! stderrLog_.empty()) {
107         fd = ::open(stdoutLog_.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666);
108         if (fd < 0)
109             throw SystemException("::open()");
110         stderr_ = fd;
111     }
112 }
113
114 prefix_ void senf::Daemon::pidFile(std::string const & f)
115 {
116     pidfile_ = f;
117 }
118
119 namespace {
120     bool signaled (false);
121     void waitusr(int) {
122         signaled = true;
123     }
124 }
125
126 prefix_ void senf::Daemon::detach()
127 {
128     if (daemonize_ && ! detached_) {
129         // Wow .. ouch .. 
130         // To ensure all data is written to the console log file in the correct order, we suspend
131         // execution here until the parent process tells us to continue via SIGUSR1: We block
132         // SIGUSR1 and install our own signal handler saving the old handler and signal mask. Then
133         // we close stdin/stderr which will send a HUP condition to the parent process. We wait for
134         // SIGUSR1 and reinstall the old signal mask and action.
135         ::sigset_t oldsig;
136         ::sigset_t usrsig;
137         ::sigemptyset(&usrsig);
138         LIBC_CALL( ::sigaddset, (&usrsig, SIGUSR1) );
139         LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &usrsig, &oldsig) );
140         struct ::sigaction oldact;
141         struct ::sigaction usract;
142         ::memset(&usract, 0, sizeof(usract));
143         usract.sa_handler = &waitusr;
144         LIBC_CALL( ::sigaction, (SIGUSR1, &usract, &oldact) );
145         ::sigset_t waitsig (oldsig);
146         LIBC_CALL( ::sigdelset, (&waitsig, SIGUSR1) );
147
148         LIBC_CALL_RV( nul, ::open, ("/dev/null", O_WRONLY) );
149         LIBC_CALL( ::dup2, (stdout_ == -1 ? nul : stdout_, 1) );
150         LIBC_CALL( ::dup2, (stderr_ == -1 ? nul : stderr_, 2) );
151         LIBC_CALL( ::close, (nul) );
152
153         signaled = false;
154         while (! signaled) {
155             ::sigsuspend(&waitsig);
156             if (errno != EINTR)
157                 throw SystemException("::sigsuspend()");
158         }
159
160         LIBC_CALL( ::sigaction, (SIGUSR1, &oldact, 0) );
161         LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
162
163         detached_ = true;
164     }
165 }
166
167 namespace {
168     /* Purposely *not* derived from std::exception */
169     struct DaemonExitException {
170         DaemonExitException(unsigned c) : code(c) {}
171         unsigned code;
172     };
173 }
174
175 prefix_ void senf::Daemon::exit(unsigned code)
176 {
177     throw DaemonExitException(code);
178 }
179
180 prefix_ int senf::Daemon::start(int argc, char const ** argv)
181 {
182     argc_ = argc;
183     argv_ = argv;
184
185     try {
186         configure();
187
188         if (daemonize_) {
189             openLog();
190             fork();
191         }
192         if (! pidfile_.empty() && ! pidfileCreate()) {
193             std::cerr << "\n*** PID file '" << pidfile_ << "' creation failed. Daemon running ?" 
194                       << std::endl;
195             return 1;
196         }
197
198         main();
199     }
200     catch (DaemonExitException & e) {
201         return e.code;
202     }
203
204 #ifndef SENF_DEBUG
205
206     catch (std::exception & e) {
207         std::cerr << "\n*** Fatal exception: " << e.what() << std::endl;
208         return 1;
209     }
210     catch (...) {
211         std::cerr << "\n*** Fatal exception: (unknown)" << std::endl;
212         return 1;
213     }
214
215 #   endif
216
217     return 0;
218 }
219
220 ////////////////////////////////////////
221 // protected members
222
223 prefix_ senf::Daemon::Daemon()
224     : argc_(0), argv_(0), daemonize_(true), stdout_(-1), stderr_(-1), pidfile_(""),
225       detached_(false)
226 {}
227
228 ////////////////////////////////////////
229 // private members
230
231 prefix_ void senf::Daemon::configure()
232 {
233     for (int i (1); i<argc_; ++i) {
234         if (argv_[i] == std::string("--no-daemon"))
235             daemonize(false);
236         else if (boost::starts_with(argv_[i], std::string("--console-log="))) {
237             std::string arg (std::string(argv_[i]), 14u);
238             std::string::size_type komma (arg.find(','));
239             if (komma == std::string::npos) {
240                 boost::trim(arg);
241                 if (arg == std::string("none")) consoleLog("");
242                 else if (!arg.empty())          consoleLog(arg);
243             } else {
244                 std::string arg1 (arg,0,komma);
245                 std::string arg2 (arg,komma+1);
246                 boost::trim(arg1);
247                 boost::trim(arg2);
248                 if (arg1 == std::string("none")) consoleLog("",StdOut);
249                 else if (! arg1.empty() )        consoleLog(arg1, StdOut);
250                 if (arg2 == std::string("none")) consoleLog("",StdErr);
251                 else if (! arg2.empty() )        consoleLog(arg2, StdErr);
252             }
253         }
254         else if (boost::starts_with(argv_[i], std::string("--pid-file="))) 
255             pidFile(std::string(std::string(argv_[i]), 11u));
256     }
257 }
258
259 prefix_ void senf::Daemon::main()
260 {
261     init();
262     detach();
263     run();
264 }
265
266 prefix_ void senf::Daemon::init()
267 {}
268
269 prefix_ void senf::Daemon::run()
270 {}
271
272 prefix_ void senf::Daemon::fork()
273 {
274     int coutpipe[2];
275     int cerrpipe[2];
276
277     LIBC_CALL_RV( nul, ::open, ("/dev/null", O_RDONLY) );
278     LIBC_CALL( ::dup2, (nul, 0) );
279     LIBC_CALL( ::close, (nul) );
280     LIBC_CALL( ::pipe, (coutpipe) );
281     LIBC_CALL( ::pipe, (cerrpipe) );
282
283     // We need to block the SIGCHLD signal here so we don't miss it, if the child
284     // dies immediately
285     ::sigset_t oldsig;
286     ::sigset_t cldsig;
287     ::sigemptyset(&cldsig);
288     LIBC_CALL( ::sigaddset, (&cldsig, SIGCHLD) );
289     LIBC_CALL( ::sigprocmask, (SIG_BLOCK, &cldsig, &oldsig) );
290     
291     LIBC_CALL_RV( pid, ::fork, () );
292
293     if (pid == 0) {
294         // Daemon process
295
296         LIBC_CALL( ::dup2, (coutpipe[1],1) );
297         LIBC_CALL( ::dup2, (cerrpipe[1],2) );
298         LIBC_CALL( ::close, (coutpipe[0]) );
299         LIBC_CALL( ::close, (coutpipe[1]) );
300         LIBC_CALL( ::close, (cerrpipe[0]) );
301         LIBC_CALL( ::close, (cerrpipe[1]) );
302         LIBC_CALL( ::setsid, () );
303         LIBC_CALL( ::sigprocmask, (SIG_SETMASK, &oldsig, 0) );
304         return;
305     }
306
307     // Ouch ... ensure, the daemon watcher does not remove the pidfile ...
308     pidfile_ = "";
309     
310     LIBC_CALL( ::close, (coutpipe[1]) );
311     LIBC_CALL( ::close, (cerrpipe[1]) );
312
313     detail::DaemonWatcher watcher (pid, coutpipe[0], cerrpipe[0], stdout_, stderr_);
314     watcher.run();
315
316     ::_exit(0);
317 }
318
319 prefix_ bool senf::Daemon::pidfileCreate()
320 {
321     // Create temporary file pidfile_.hostname.pid and hard-link it to pidfile_ If the hardlink
322     // fails, the pidfile exists. If the link count of the temporary file is not 2 after this, there
323     // was some race condition, probably over NFS.
324
325     std::string tempname;
326     boost::format linkErrorFormat(" Could not link \"%1%\" to \"%2%\".");
327
328     {
329         char hostname[HOST_NAME_MAX+1];
330         LIBC_CALL( ::gethostname, (hostname, HOST_NAME_MAX+1) );
331         hostname[HOST_NAME_MAX] = 0;
332         std::stringstream tempname_s;
333         tempname_s << pidfile_ << "." << hostname << "." << ::getpid();
334         tempname = tempname_s.str();
335     }
336
337     while (1) {
338         {
339             std::ofstream pidf (tempname.c_str());
340             pidf << ::getpid() << std::endl;
341         }
342
343         if (::link(tempname.c_str(), pidfile_.c_str()) < 0) {
344             if (errno != EEXIST) 
345                 throw SystemException("::link()")
346                     << linkErrorFormat % pidfile_.c_str() % tempname.c_str();
347         }
348         else {
349             struct ::stat s;
350             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
351             LIBC_CALL( ::unlink, (tempname.c_str()) );
352             return s.st_nlink == 2;
353         }
354
355         // pidfile exists. Check, whether the pid in the pidfile still exists.
356         {
357             int old_pid (-1);
358             std::ifstream pidf (pidfile_.c_str());
359             if ( ! (pidf >> old_pid)
360                  || old_pid < 0 
361                  || ::kill(old_pid, 0) >= 0 
362                  || errno == EPERM )
363                 return false;
364         }
365
366         // If we reach this point, the pid file exists but the process mentioned within the
367         // pid file does *not* exists. We assume, the pid file to be stale.
368
369         // I hope, the following procedure is without race condition: We remove our generated
370         // temporary pid file and recreate it as hard-link to the old pid file. Now we check, that
371         // the hard-link count of this file is 2. If it is not, we terminate, since someone else
372         // must have already created his hardlink. We then truncate the file and write our pid.
373
374         LIBC_CALL( ::unlink, (tempname.c_str() ));
375         if (::link(pidfile_.c_str(), tempname.c_str()) < 0) {
376             if (errno != ENOENT)
377                 throw SystemException("::link()")
378                     << linkErrorFormat % tempname.c_str() % pidfile_.c_str();
379             // Hmm ... the pidfile mysteriously disappeared ... try again.
380             continue;
381         }
382
383         {
384             struct ::stat s;
385             LIBC_CALL( ::stat, (tempname.c_str(), &s) );
386             if (s.st_nlink != 2) {
387                 LIBC_CALL( ::unlink, (tempname.c_str()) );
388                 return false;
389             }
390         }
391         
392         {
393             std::ofstream pidf (tempname.c_str());
394             pidf << ::getpid() << std::endl;
395         }
396
397         LIBC_CALL( ::unlink, (tempname.c_str()) );
398         break;
399     }
400     return true;
401 }
402
403 ///////////////////////////////////////////////////////////////////////////
404 // senf::detail::DaemonWatcher
405
406 prefix_ senf::detail::DaemonWatcher::DaemonWatcher(int pid, int coutpipe, int cerrpipe,
407                                                    int stdout, int stderr)
408     : childPid_(pid), coutpipe_(coutpipe), cerrpipe_(cerrpipe), stdout_(stdout),
409       stderr_(stderr), sigChld_(false),
410       coutForwarder_(coutpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 1)), 
411       cerrForwarder_(cerrpipe_, boost::bind(&DaemonWatcher::pipeClosed, this, 2)) 
412 {
413     coutForwarder_.addTarget(1);
414     if (stdout_ >= 0)
415         coutForwarder_.addTarget(stdout_);
416     cerrForwarder_.addTarget(2);
417     if (stderr_ >= 0)
418         cerrForwarder_.addTarget(stderr_);
419 }
420
421 prefix_ void senf::detail::DaemonWatcher::run()
422 {
423     Scheduler::instance().registerSignal(SIGCHLD, senf::membind(&DaemonWatcher::sigChld, this));
424     Scheduler::instance().process();
425 }
426
427 ////////////////////////////////////////
428 // private members
429
430 prefix_ void senf::detail::DaemonWatcher::pipeClosed(int id)
431 {
432     switch (id) {
433     case 1 : coutpipe_ = -1; break;
434     case 2 : cerrpipe_ = -1; break;
435     }
436
437     if (coutpipe_ == -1 && cerrpipe_ == -1) {
438         if (sigChld_)
439             childDied(); // does not return
440         if (::kill(childPid_, SIGUSR1) < 0)
441             if (errno != ESRCH) throw SystemException("::kill()");
442         Scheduler::instance().timeout(
443             Scheduler::instance().eventTime() + ClockService::seconds(1),
444             senf::membind(&DaemonWatcher::childOk, this));
445     }
446 }
447
448 prefix_ void senf::detail::DaemonWatcher::sigChld()
449 {
450     sigChld_ = true;
451     if (coutpipe_ == -1 && cerrpipe_ == -1)
452         childDied(); // does not return
453 }
454
455 prefix_ void senf::detail::DaemonWatcher::childDied()
456 {
457     int status (0);
458     if (::waitpid(childPid_,&status,0) < 0) throw SystemException("::waitpid()");
459     if (WIFSIGNALED(status)) {
460         ::signal(WTERMSIG(status),SIG_DFL);
461         ::kill(::getpid(), WTERMSIG(status));
462         // should not be reached
463         ::_exit(1);
464     }
465     if (WEXITSTATUS(status) == 0)
466         ::_exit(1);
467     ::_exit(WEXITSTATUS(status));
468 }
469
470 prefix_ void senf::detail::DaemonWatcher::childOk()
471 {
472     Scheduler::instance().terminate();
473 }
474
475 ///////////////////////////////////////////////////////////////////////////
476 // senf::detail::DaemonWatcher::Forwarder
477
478 prefix_ senf::detail::DaemonWatcher::Forwarder::Forwarder(int src, Callback cb)
479     : src_(src), cb_(cb)
480 {
481     Scheduler::instance().add(src_, senf::membind(&Forwarder::readData, this),
482                               Scheduler::EV_READ);
483 }
484
485 prefix_ senf::detail::DaemonWatcher::Forwarder::~Forwarder()
486 {
487     if (src_ != -1)
488         Scheduler::instance().remove(src_);
489     
490     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
491         if (i->offset >= buffer_.size())
492             Scheduler::instance().remove(i->fd);
493 }
494
495 prefix_ void senf::detail::DaemonWatcher::Forwarder::addTarget(int fd)
496 {
497     Target target = { fd, 0 };
498     targets_.push_back(target);
499 }
500
501 prefix_ void senf::detail::DaemonWatcher::Forwarder::readData(Scheduler::EventId event)
502 {
503     char buf[1024];
504     int n (0);
505
506     while (1) {
507         n = ::read(src_,buf,1024);
508         if (n<0) {
509             if (errno != EINTR) throw SystemException("::read()");
510         } else 
511             break;
512     }
513
514     if (n == 0) {
515         // Hangup
516         Scheduler::instance().remove(src_);
517         if (buffer_.empty())
518             cb_(); 
519         src_ = -1;
520         return;
521     }
522
523     if (targets_.empty())
524         return;
525
526     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
527         if (i->offset >= buffer_.size())
528             Scheduler::instance().add( i->fd, 
529                                        boost::bind(&Forwarder::writeData, this, _1, i),
530                                        Scheduler::EV_WRITE );
531
532     buffer_.insert(buffer_.end(), buf, buf+n);
533 }
534
535 prefix_ void senf::detail::DaemonWatcher::Forwarder::writeData(Scheduler::EventId event,
536                                                                Targets::iterator target)
537 {    
538     if (event != Scheduler::EV_WRITE) {
539         // Broken pipe while writing data ? Not much, we can do here, we just drop the data
540         Scheduler::instance().remove(target->fd);
541         targets_.erase(target);
542         if (targets_.empty() && src_ == -1)
543             cb_();
544         return;
545     }
546
547     char buf[1024];
548     int n (buffer_.size() - target->offset > 1024 ? 1024 : buffer_.size() - target->offset);
549     std::copy(buffer_.begin() + target->offset, buffer_.begin() + target->offset + n, buf);
550
551     int w (::write(target->fd, buf, n));
552     if (w < 0) {
553         if (errno != EINTR) throw SystemException("::write()");
554         return;
555     }
556     target->offset += w;
557
558     n = std::min_element(
559         targets_.begin(), targets_.end(),
560         boost::bind(&Target::offset, _1) < boost::bind(&Target::offset, _2))->offset;
561
562     buffer_.erase(buffer_.begin(), buffer_.begin()+n);
563
564     for (Targets::iterator i (targets_.begin()); i != targets_.end(); ++i)
565         i->offset -= n;
566
567     if (target->offset >= buffer_.size())
568         Scheduler::instance().remove(target->fd);
569     if (src_ == -1 && (buffer_.empty() || targets_.empty()))
570         cb_();
571 }
572
573 #undef LIBC_CALL
574 #undef LIBC_CALL_RV
575
576 ///////////////////////////////cc.e////////////////////////////////////////
577 #undef prefix_
578 //#include "Daemon.mpp"
579
580 \f
581 // Local Variables:
582 // mode: c++
583 // fill-column: 100
584 // comment-column: 40
585 // c-file-style: "senf"
586 // indent-tabs-mode: nil
587 // ispell-local-dictionary: "american"
588 // compile-command: "scons -u test"
589 // End: