90ba9ef31e3e331c0480a8923be94fa5bc7b76f5
[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     : files_(0), timerIdCounter_(0), epollFd_ (epoll_create(EPollInitialSize)), terminate_(false),
58       eventTime_(0), eventEarly_(ClockService::milliseconds(11)), eventAdjust_(0)
59 {
60     if (epollFd_<0)
61         throwErrno();
62
63     if (::pipe(sigpipe_) < 0)
64         throwErrno();
65
66     int flags (::fcntl(sigpipe_[1],F_GETFL));
67     if (flags < 0) 
68         throwErrno();
69     flags |= O_NONBLOCK;
70     if (::fcntl(sigpipe_[1], F_SETFL, flags) < 0) 
71         throwErrno();
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         throwErrno();
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     if (eventMask == 0)
108         return;
109
110     FdTable::iterator i (fdTable_.find(fd));
111     int action (EPOLL_CTL_MOD);
112     if (i == fdTable_.end()) {
113         action = EPOLL_CTL_ADD;
114         i = fdTable_.insert(std::make_pair(fd, EventSpec())).first;
115     }
116     if (i->second.epollMask() == 0) {
117         action = EPOLL_CTL_ADD;
118         fdErase_.erase( std::remove(fdErase_.begin(), fdErase_.end(), unsigned(fd)),
119                         fdErase_.end() );
120     }
121
122     if (eventMask & EV_READ)  i->second.cb_read = cb;
123     if (eventMask & EV_PRIO)  i->second.cb_prio = cb;
124     if (eventMask & EV_WRITE) i->second.cb_write = cb;
125
126     epoll_event ev;
127     memset(&ev,0,sizeof(ev));
128     ev.events = i->second.epollMask();
129     ev.data.fd = fd;
130
131     if (! i->second.file && epoll_ctl(epollFd_, action, fd, &ev) < 0) {
132         if (errno == EPERM) {
133             // Argh ... epoll does not support ordinary files :-( :-(
134             i->second.file = true;
135             ++ files_;
136         }
137         else
138             throwErrno("::epoll_ctl()");
139     }
140 }
141
142 prefix_ void senf::Scheduler::do_remove(int fd, int eventMask)
143 {
144     if (eventMask == 0)
145         return;
146
147     FdTable::iterator i (fdTable_.find(fd));
148     if (i == fdTable_.end())
149         return;
150
151     if (eventMask & EV_READ)  i->second.cb_read = 0;
152     if (eventMask & EV_PRIO)  i->second.cb_prio = 0;
153     if (eventMask & EV_WRITE) i->second.cb_write = 0;
154
155     epoll_event ev;
156     memset(&ev,0,sizeof(ev));
157     ev.events = i->second.epollMask();
158     ev.data.fd = fd;
159
160     int action (EPOLL_CTL_MOD);
161     bool file (i->second.file);
162     if (ev.events==0) {
163         action = EPOLL_CTL_DEL;
164         fdErase_.push_back(fd);
165     }
166
167     if (! file && epoll_ctl(epollFd_, action, fd, &ev) < 0)
168         throwErrno("::epoll_ctl()");
169     if (file)
170         -- files_;
171 }
172
173 prefix_ void senf::Scheduler::registerSigHandlers()
174 {
175     for (unsigned signal (1); signal < sigHandlers_.size(); ++signal) {
176         if (sigHandlers_[signal]) {
177             struct ::sigaction sa;
178             sa.sa_sigaction = & Scheduler::sigHandler;
179             sa.sa_mask = sigset_;
180             sa.sa_flags = SA_SIGINFO;
181             if (signal == SIGCHLD)
182                 sa.sa_flags |= SA_NOCLDSTOP;
183             if (::sigaction(signal, &sa, 0) < 0)
184                 throwErrno();
185         }
186     }
187 }
188
189 prefix_ void senf::Scheduler::sigHandler(int signal, ::siginfo_t * siginfo, void *)
190 {
191     // This is a bit unsafe. Better write single bytes and place the siginfo into an explicit
192     // queue. Since signals are only unblocked during epoll_wait, we even wouldn't need to
193     // synchronize access to that queue any further.
194
195     ::write(instance().sigpipe_[1], siginfo, sizeof(*siginfo));
196
197     // We ignore errors. The file handle is set to non-blocking IO. If any failure occurs (pipe
198     // full), the signal will be dropped. That's like kernel signal handling which may also drop
199     // signals.
200 }
201
202 prefix_ int senf::Scheduler::EventSpec::epollMask()
203     const
204 {
205     int mask (0);
206     if (cb_read)  mask |= EPOLLIN;
207     if (cb_prio)  mask |= EPOLLPRI;
208     if (cb_write) mask |= EPOLLOUT;
209     return mask;
210 }
211
212 prefix_ void senf::Scheduler::process()
213 {
214     terminate_ = false;
215     eventTime_ = ClockService::now();
216     while (! terminate_) {
217
218         // Since a callback may have disabled further timers, we need to check for canceled timeouts
219         // again.
220
221         while (! timerQueue_.empty()) {
222             TimerMap::iterator i (timerQueue_.top());
223             if (! i->second.canceled)
224                 break;
225             timerMap_.erase(i);
226             timerQueue_.pop();
227         }
228
229         for (FdEraseList::iterator i (fdErase_.begin()); i != fdErase_.end(); ++i) 
230             fdTable_.erase(*i);
231         fdErase_.clear();
232
233         int timeout (-1);
234         if (files_ > 0)
235             timeout = 0;
236         else {
237             if (timerQueue_.empty()) {
238                 if (fdTable_.empty())
239                     break;
240             }
241             else {
242                 ClockService::clock_type delta (
243                     (timerQueue_.top()->second.timeout - eventTime_ + eventAdjust_)/1000000UL);
244                 timeout = delta < 0 ? 0 : delta;
245             }
246         }
247
248         ///\todo Handle more than one epoll_event per call
249         struct epoll_event ev;
250         
251         ::sigprocmask(SIG_UNBLOCK, &sigset_, 0);
252         int events (epoll_wait(epollFd_, &ev, 1, timeout));
253         ::sigprocmask(SIG_BLOCK, &sigset_, 0);
254
255         if (events<0)
256             if (errno != EINTR)
257                 throwErrno();
258
259         eventTime_ = ClockService::now();
260
261         // We always run timeout handlers. This is important, even if a file-descriptor is signaled
262         // since some descriptors (e.g. real files) will *always* be ready and we still may want to
263         // handle timers.  Time handlers are run before file events to not delay them unnecessarily.
264
265         while (! timerQueue_.empty()) {
266             TimerMap::iterator i (timerQueue_.top());
267             if (i->second.canceled)
268                 ;
269             else if (i->second.timeout <= eventTime_ + eventEarly_)
270                 i->second.cb();
271             else
272                 break;
273             timerQueue_.pop();
274             timerMap_.erase(i);
275         }
276
277         // Check the signal queue
278         if (events > 0 && ev.data.fd == sigpipe_[0]) {
279             ::siginfo_t siginfo;
280             if (::read(sigpipe_[0], &siginfo, sizeof(siginfo)) < int(sizeof(siginfo))) {
281                 // We ignore truncated records which may only occur if the signal
282                 // queue became filled up
283                 SENF_LOG((senf::log::IMPORTANT)("Truncated signal record!"));
284                 continue;
285             }
286             if (siginfo.si_signo < int(sigHandlers_.size()) && sigHandlers_[siginfo.si_signo])
287                 sigHandlers_[siginfo.si_signo]();
288             continue;
289         }
290
291         for (FdTable::iterator i = fdTable_.begin(); i != fdTable_.end(); ++i) {
292             EventSpec & spec (i->second);
293
294             if (! (spec.file || (events > 0 && i->first == ev.data.fd)))
295                 continue;
296                 
297             unsigned extraFlags (0);
298             unsigned mask (spec.file ? spec.epollMask() : ev.events);
299
300             if (mask & EPOLLHUP) extraFlags |= EV_HUP;
301             if (mask & EPOLLERR) extraFlags |= EV_ERR;
302
303             if (mask & EPOLLIN) {
304                 BOOST_ASSERT(spec.cb_read);
305                 spec.cb_read(EventId(EV_READ | extraFlags));
306             }
307             else if (mask & EPOLLPRI) {
308                 BOOST_ASSERT(spec.cb_prio);
309                 spec.cb_prio(EventId(EV_PRIO | extraFlags));
310             }
311             else if (mask & EPOLLOUT) {
312                 BOOST_ASSERT(spec.cb_write);
313                 spec.cb_write(EventId(EV_WRITE | extraFlags));
314             }
315             else {
316                 // This branch is only taken, if HUP or ERR is signaled but none of IN/OUT/PRI. 
317                 // In this case we will signal all registered callbacks. The callbacks must be
318                 // prepared to be called multiple times if they are registered to more than
319                 // one event.
320                 if (spec.cb_write) 
321                     spec.cb_write(EventId(extraFlags));
322                 if (spec.cb_prio) 
323                     spec.cb_prio(EventId(extraFlags));
324                 if (spec.cb_read) 
325                     spec.cb_read(EventId(extraFlags));
326             }
327         }
328     }
329 }
330
331 ///////////////////////////////////////////////////////////////////////////
332 // senf::SchedulerLogTimeSource
333
334 prefix_ boost::posix_time::ptime senf::SchedulerLogTimeSource::operator()()
335     const
336 {
337     return ClockService::abstime(Scheduler::instance().eventTime());
338 }
339
340 ///////////////////////////////cc.e////////////////////////////////////////
341 #undef prefix_
342
343 \f
344 // Local Variables:
345 // mode: c++
346 // fill-column: 100
347 // c-file-style: "senf"
348 // indent-tabs-mode: nil
349 // ispell-local-dictionary: "american"
350 // compile-command: "scons -u test"
351 // comment-column: 40
352 // End: