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