Scheduler: Add POSIX/UNIX signal support
[senf.git] / Scheduler / Scheduler.cc
1 // $Id$
2 //
3 // Copyright (C) 2006
4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
6 //     Stefan Bund <stefan.bund@fokus.fraunhofer.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 Scheduler non-inline non-template implementation
25
26     \idea Implement signal handling (See source for more discussion
27     about this)
28
29     \idea Multithreading support: To support multithreading, the
30     static member Scheduler::instance() must return a thread-local
31     value (that is Scheduler::instance() must allocate one Scheduler
32     instance per thread). Another possibility would be to distribute
33     the async load unto several threads (one scheduler for multiple
34     threads)
35  */
36
37 // Here a basic concept of how to add signal support to the scheduler:
38 //
39 // ... no, I had overlooked one race condition. So back to the signal-pipe approach ...
40
41 #include "Scheduler.hh"
42 //#include "Scheduler.ih"
43
44 // Custom includes
45 #include <errno.h>
46 #include <sys/epoll.h>
47 #include <unistd.h>
48 #include <fcntl.h>
49 #include "../Utils/Exception.hh"
50
51 static const int EPollInitialSize = 16;
52
53 #define prefix_
54 ///////////////////////////////cc.p////////////////////////////////////////
55
56 prefix_ senf::Scheduler::Scheduler()
57     : timerIdCounter_(0), epollFd_ (epoll_create(EPollInitialSize)), terminate_(false),
58       eventTime_(0), eventEarly_(ClockService::milliseconds(11)), eventAdjust_(0)
59 {
60     if (epollFd_<0)
61         throw SystemException(errno);
62
63     if (::pipe(sigpipe_) < 0)
64         throw SystemException(errno);
65
66     int flags (::fcntl(sigpipe_[1],F_GETFL));
67     if (flags < 0) 
68         throw SystemException(errno);
69     flags |= O_NONBLOCK;
70     if (::fcntl(sigpipe_[1], F_SETFL, flags) < 0) 
71         throw SystemException(errno);
72
73     ::epoll_event ev;
74     ::memset(&ev, 0, sizeof(ev));
75     ev.events = EV_READ;
76     ev.data.fd = sigpipe_[0];
77     if (::epoll_ctl(epollFd_, EPOLL_CTL_ADD, sigpipe_[0], &ev) < 0)
78         throw SystemException(errno);
79 }
80
81 prefix_ void senf::Scheduler::registerSignal(unsigned signal, SimpleCallback const & cb)
82 {
83     ::sigset_t sig;
84     ::sigemptyset(&sig);
85     if (::sigaddset(&sig, signal) < 0)
86         throw InvalidSignalNumberException();
87     ::sigprocmask(SIG_BLOCK, &sig, 0);
88     ::sigaddset(&sigset_, signal);
89     if (sigHandlers_.size() <= signal)
90         sigHandlers_.resize(signal+1);
91     sigHandlers_[signal] = cb;
92
93     registerSigHandlers();
94 }
95
96 prefix_ void senf::Scheduler::unregisterSignal(unsigned signal)
97 {
98     if (::sigdelset(&sigset_, signal) < 0)
99         throw InvalidSignalNumberException();
100     sigHandlers_[signal] = 0;
101     ::signal(signal, SIG_DFL);
102     registerSigHandlers();
103 }
104
105 prefix_ void senf::Scheduler::do_add(int fd, FdCallback const & cb, int eventMask)
106 {
107     FdTable::iterator i (fdTable_.find(fd));
108     int action (EPOLL_CTL_MOD);
109     if (i == fdTable_.end()) {
110         action = EPOLL_CTL_ADD;
111         i = fdTable_.insert(std::make_pair(fd, EventSpec())).first;
112     }
113
114     if (eventMask & EV_READ)  i->second.cb_read = cb;
115     if (eventMask & EV_PRIO)  i->second.cb_prio = cb;
116     if (eventMask & EV_WRITE) i->second.cb_write = cb;
117
118     epoll_event ev;
119     memset(&ev,0,sizeof(ev));
120     ev.events = i->second.epollMask();
121     ev.data.fd = fd;
122
123     if (epoll_ctl(epollFd_, action, fd, &ev)<0)
124         throw SystemException(errno);
125 }
126
127 prefix_ void senf::Scheduler::do_remove(int fd, int eventMask)
128 {
129     FdTable::iterator i (fdTable_.find(fd));
130     if (i == fdTable_.end())
131         return;
132
133     if (eventMask & EV_READ)  i->second.cb_read = 0;
134     if (eventMask & EV_PRIO)  i->second.cb_prio = 0;
135     if (eventMask & EV_WRITE) i->second.cb_write = 0;
136
137     epoll_event ev;
138     memset(&ev,0,sizeof(ev));
139     ev.events = i->second.epollMask();
140     ev.data.fd = fd;
141
142     int action (EPOLL_CTL_MOD);
143     if (ev.events==0) {
144         action = EPOLL_CTL_DEL;
145         fdTable_.erase(i);
146     }
147
148     if (epoll_ctl(epollFd_, action, fd, &ev)<0)
149         throw SystemException(errno);
150 }
151
152 prefix_ void senf::Scheduler::registerSigHandlers()
153 {
154     for (unsigned signal; signal < sigHandlers_.size(); ++signal)
155         if (sigHandlers_[signal]) {
156             struct ::sigaction sa;
157             sa.sa_sigaction = & Scheduler::sigHandler;
158             sa.sa_mask = sigset_;
159             sa.sa_flags = SA_SIGINFO;
160             if (signal == SIGCHLD)
161                 sa.sa_flags |= SA_NOCLDSTOP;
162             if (::sigaction(signal, &sa, 0) < 0)
163                 throw SystemException(errno);
164         }
165 }
166
167 prefix_ void senf::Scheduler::sigHandler(int signal, ::siginfo_t * siginfo, void *)
168 {
169     // This is a bit unsafe. Better write single bytes and place the siginfo into an explicit
170     // queue. Since signals are only unblocked during epoll_wait, we even wouldn't need to
171     // synchronize access to that queue any further.
172
173     ::write(instance().sigpipe_[1], siginfo, sizeof(siginfo));
174
175     // We ignore errors. The file handle is set to non-blocking IO. If any failure occurs (pipe
176     // full), the signal will be dropped. That's like kernel signal handling which may also drop
177     // signals.
178 }
179
180 prefix_ int senf::Scheduler::EventSpec::epollMask()
181     const
182 {
183     int mask (0);
184     if (cb_read)  mask |= EPOLLIN;
185     if (cb_prio)  mask |= EPOLLPRI;
186     if (cb_write) mask |= EPOLLOUT;
187     return mask;
188 }
189
190 prefix_ void senf::Scheduler::process()
191 {
192     terminate_ = false;
193     eventTime_ = ClockService::now();
194     while (! terminate_) {
195
196         // Since a callback may have disabled further timers, we need to check for canceled timeouts
197         // again.
198
199         while (! timerQueue_.empty()) {
200             TimerMap::iterator i (timerQueue_.top());
201             if (! i->second.canceled)
202                 break;
203             timerMap_.erase(i);
204             timerQueue_.pop();
205         }
206
207         int timeout (-1);
208         if (timerQueue_.empty()) {
209             if (fdTable_.empty())
210                 break;
211         }
212         else {
213             ClockService::clock_type delta (
214                 (timerQueue_.top()->second.timeout - eventTime_ + eventAdjust_)/1000000UL);
215             timeout = delta < 0 ? 0 : delta;
216         }
217
218         ///\todo Handle more than one epoll_event per call
219         struct epoll_event ev;
220         
221         ::sigprocmask(SIG_UNBLOCK, &sigset_, 0);
222         int events (epoll_wait(epollFd_, &ev, 1, timeout));
223         ::sigprocmask(SIG_BLOCK, &sigset_, 0);
224
225         if (events<0)
226             if (errno != EINTR)
227                 throw SystemException(errno);
228
229         eventTime_ = ClockService::now();
230
231         // We always run timeout handlers. This is important, even if a file-descriptor is signaled
232         // since some descriptors (e.g. real files) will *always* be ready and we still may want to
233         // handle timers.  Time handlers are run before file events to not delay them unnecessarily.
234
235         while (! timerQueue_.empty()) {
236             TimerMap::iterator i (timerQueue_.top());
237             if (i->second.canceled)
238                 ;
239             else if (i->second.timeout <= eventTime_ + eventEarly_)
240                 i->second.cb();
241             else
242                 break;
243             timerQueue_.pop();
244             timerMap_.erase(i);
245         }
246
247         if (events <= 0)
248             continue;
249
250         // Check the signal queue
251         if (ev.data.fd == sigpipe_[0]) {
252             ::siginfo_t siginfo;
253             if (::read(sigpipe_[0], &siginfo, sizeof(siginfo)) < int(sizeof(siginfo)))
254                 // We ignore truncated records which may only occur if the signal
255                 // queue became filled up
256                 continue;
257             if (siginfo.si_signo < int(sigHandlers_.size()) && sigHandlers_[siginfo.si_signo])
258                 sigHandlers_[siginfo.si_signo]();
259             continue;
260         }
261
262         FdTable::iterator i = fdTable_.find(ev.data.fd);
263         BOOST_ASSERT (i != fdTable_.end() );
264         EventSpec spec (i->second);
265
266         unsigned extraFlags (0);
267         if (ev.events & EPOLLHUP) extraFlags |= EV_HUP;
268         if (ev.events & EPOLLERR) extraFlags |= EV_ERR;
269
270         if (ev.events & EPOLLIN) {
271             BOOST_ASSERT(spec.cb_read);
272             spec.cb_read(EventId(EV_READ | extraFlags));
273         }
274         else if (ev.events & EPOLLPRI) {
275             BOOST_ASSERT(spec.cb_prio);
276             spec.cb_prio(EventId(EV_PRIO | extraFlags));
277         }
278         else if (ev.events & EPOLLOUT) {
279             BOOST_ASSERT(spec.cb_write);
280             spec.cb_write(EventId(EV_WRITE | extraFlags));
281         }
282         else {
283             // This branch is only taken, if HUP or ERR is signaled but none of IN/OUT/PRI. 
284             // In this case we will signal all registered callbacks. The callbacks must be
285             // prepared to be called multiple times if they are registered to more than
286             // one event.
287             if (spec.cb_write) 
288                 spec.cb_write(EventId(extraFlags));
289             if (spec.cb_prio) 
290                 spec.cb_prio(EventId(extraFlags));
291             if (spec.cb_read) 
292                 spec.cb_read(EventId(extraFlags));
293         }
294     }
295 }
296
297 ///////////////////////////////////////////////////////////////////////////
298 // senf::SchedulerLogTimeSource
299
300 prefix_ boost::posix_time::ptime senf::SchedulerLogTimeSource::operator()()
301     const
302 {
303     return ClockService::abstime(Scheduler::instance().eventTime());
304 }
305
306 ///////////////////////////////cc.e////////////////////////////////////////
307 #undef prefix_
308
309 \f
310 // Local Variables:
311 // mode: c++
312 // fill-column: 100
313 // c-file-style: "senf"
314 // indent-tabs-mode: nil
315 // ispell-local-dictionary: "american"
316 // compile-command: "scons -u test"
317 // comment-column: 40
318 // End: