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