Fix documentation build under maverick (doxygen 1.7.1)
[senf.git] / senf / Scheduler / Scheduler.hh
1 // $Id$
2 //
3 // Copyright (C) 2006
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 Scheduler public header
25  */
26
27 #ifndef HH_SENF_Scheduler_Scheduler_
28 #define HH_SENF_Scheduler_Scheduler_ 1
29
30 // Custom includes
31 #include <boost/utility.hpp>
32 #include <senf/Utils/Logger/TimeSource.hh>
33 #include "FdEvent.hh"
34 #include "TimerEvent.hh"
35 #include "SignalEvent.hh"
36 #include "IdleEvent.hh"
37 #include "EventHook.hh"
38
39 //#include "scheduler.mpp"
40 //-/////////////////////////////////////////////////////////////////////////////////////////////////
41
42 namespace senf {
43
44 /** \brief The Scheduler interface
45
46     The %scheduler API is comprised of two parts:
47
48     \li Specific \ref sched_objects, one for each type of event.
49     \li Some <a href="#autotoc-7.">generic functions</a> implemented in the \ref senf::scheduler
50         namespace.
51
52     Events are registered via the respective event class. The (global) functions are used to enter
53     the application main-loop or query for global information.
54
55     \autotoc
56
57
58     \section sched_objects Event classes
59
60     The Scheduler is based on the RAII principle: Every event is represented by a class
61     instance. The event is registered in the constructor and removed by the destructor of that
62     instance. This implementation automatically links the lifetime of an event with the lifetime of
63     the object responsible for it's creation.
64
65     Every event registration is represented by an instance of an event specific class:
66
67     \li senf::scheduler::FdEvent for file descriptor events
68     \li senf::scheduler::TimerEvent for single-shot deadline timer events
69     \li senf::scheduler::SignalEvent for UNIX signal events
70     \li senf::scheduler::EventHook for a special event hook
71
72     These instance are owned and managed by the user of the scheduler \e not by the scheduler so the
73     RAII concept can be used.
74
75     \code
76     class SomeServer
77     {
78         SomeSocketHandle handle_;
79         senf::scheduler::FdEvent event_;
80
81     public:
82         SomeServer(SomeSocketHandle handle)
83             : handle_ (handle),
84               event_ ("SomeServer handler", senf::membind(&SomeServer::readData, this),
85                       handle, senf::scheduler::FdEvent::EV_READ)
86         {}
87
88         void readData(int events)
89         {
90             // read data from handle_, check for eof and so on.
91         }
92     };
93     \endcode
94
95     The event is defined as a class member variable. When the event member is initialized in the
96     constructor, the event is automatically registered (except if the optional \a initiallyEnabled
97     flag argument is set to \c false). The Destructor will automatically remove the event from the
98     scheduler and ensure, that no dead code is called accidentally.
99
100     The process is the same for the other event types or when registering multiple events. For
101     detailed information on the constructor arguments and other features see the event class
102     documentation referenced below.
103
104
105     \section sched_handlers Specifying handlers
106
107     All handlers are specified as generic <a
108     href="http://www.boost.org/doc/libs/release/libs/functional/index.html">Boost.Function</a>
109     objects. This allows to pass any callable as a handler. Depending on the type of handler,
110     some additional arguments may be passed to the handler by the %scheduler.
111
112     If you need to pass additional information to your handler, use <a
113     href="http://www.boost.org/doc/libs/release/libs/bind/bind.html">Boost.Bind</a>:
114     \code
115     // Handle callback function
116     void callback(UDPv4ClientSocketHandle handle, senf::Scheduler::EventId event) {..}
117     // Pass 'handle' as additional first argument to callback()
118     senf::scheduler::FdEvent event ("name", boost::bind(&callback, handle, _1),
119                                     handle, senf::scheduler::FdEvent::EV_READ);
120      // Timeout function
121     void timeout( int n) {..}
122     // Call timeout() handler with argument 'n'
123     senf::scheduler::TimerEvent timer ("name", boost::bind(&timeout, n),
124                                        senf::ClockService::now() + senf::ClockService::seconds(1));
125     \endcode
126
127     To use member-functions as callbacks, use either <a
128     href="http://www.boost.org/doc/libs/release/libs/bind/bind.html">Boost.Bind</a> or senf::membind()
129     \code
130     // e.g. in Foo::Foo() constructor:
131     Foo::Foo()
132         : handle_ (...),
133           readevent_ ("Foo read", senf::membind(&Foo::callback, this),
134                       handle_, senf::scheduler::FdEvent::EV_READ)
135     { ... }
136     \endcode
137
138     The handler is identified by an arbitrary, user specified name. This name is used in error
139     messages to identify the failing handler.
140
141
142     \section sched_exec Executing the Scheduler
143
144     To enter the scheduler main-loop, call
145
146     \code
147     senf::scheduler::process();
148     \endcode
149
150     This call will only return in two cases:
151
152     \li When a handler calls senf::scheduler::terminate()
153     \li When there is no active file descriptor or timer event.
154
155     Additional <a href="#autotoc-7.">generic functions</a> provide information and %scheduler
156     parameters.
157
158     \section sched_container Event objects and container classes
159
160     As the event objects are \e not copyable, they cannot be placed into ordinary
161     containers. However, it is quite simple to use pointer containers to hold event instances:
162
163     \code
164     #include <boost/ptr_container/ptr_map.hpp>
165     #include <boost/bind.hpp>
166
167     class Foo
168     {
169     public:
170         void add(int fd)
171         {
172             fdEvents.insert(
173                 fd,
174                 new senf::scheduler::FdEvent("foo", boost::bind(&callback, this, fd, _1), fd,
175                                              senf::scheduler::FdEvent::EV_READ) );
176         }
177
178         void callback(int fd, int events)
179         {
180             FdEvent & event (fdEvents_[fd]);
181
182             // ...
183
184             if (complete)
185                 fdEvents_.remove(fd)
186         }
187
188     private:
189         boost::ptr_map<int, FdEvent> fdEvents_;
190     };
191     \endcode
192
193     The pointer container API is (almost) completely identical to the corresponding standard library
194     container API. The only difference is, that all elements added to the container \e must be
195     created via \c new and that the pointer containers themselves are \e not copyable (ok, they are,
196     if the elements are cloneable ...). See <a
197     href="http://www.boost.org/doc/libs/release/libs/ptr_container/doc/ptr_container.html">Boost.PointerContainer</a>
198     for the pointer container library reference.
199
200
201     \section sched_signals Signals and the Watchdog
202
203     To secure against blocking callbacks, the %scheduler implementation includes a watchdog
204     timer. This timer will produce a warning message on the standard error stream when a single
205     callback is executing for more than the watchdog timeout value. Since the scheduler
206     implementation is completely single threaded, we cannot terminate the callback but at least we
207     can produce an informative message and optionally the program can be aborted.
208
209     The watchdog is controlled using the watchdogTimeout(), watchdogEvents() and watchdogAbort().
210     functions.
211
212     The watchdog is implemented using a free running interval timer. The watchdog signal (\c SIGURG)
213     must \e not be blocked. If signals need to be blocked for some reason, those regions will not be
214     checked by the watchdog. If a callback blocks, the watchdog has no chance to interrupt the
215     process.
216
217     \warning Since the watchdog is free running for performance reasons, every callback must expect
218         signals to happen. Signals \e will certainly happen since the watchdog signal is generated
219         periodically (which does not necessarily generate a watchdog event ...)
220
221     Additional signals (\c SIGALRM) may occur when using using hires timers on kernel/glibc
222     combinations which do not support timerfd(). On such systems, hires timers are implemented using
223     POSIX timers which generate a considerable number of additional signals.
224
225     \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
226         over e.g. NFS.
227   */
228 namespace scheduler {
229
230     /** \brief Event handler main loop
231
232         This member must be called at some time to enter the event handler main loop. Only while
233         this function is running any events are handled. The call will return if
234         \li a callback calls terminate()
235         \li the run queue becomes empty.
236      */
237     void process();
238
239     /** \brief \c true, if scheduler is running, \c false otherwise */
240     bool running();
241
242     /** \brief Called by callbacks to terminate the main loop
243
244         This member may be called by any callback to tell the main loop to terminate. The main loop
245         will return to it's caller after the currently running callback returns.
246      */
247     void terminate();
248
249     /** \brief Immediately rescheduler
250
251         Calling yield() will cause the scheduler to terminate the current queue run and immediately
252         rescheduler all pending tasks.
253      */
254     void yield();
255
256     /** \brief Return timestamp of last event
257
258         This is the timestamp, the last event has been signaled. This is the real time at which the
259         event is delivered \e not the time it should have been delivered (in the case of timers).
260      */
261     ClockService::clock_type eventTime();
262
263     /** \brief Return (approximate) current time
264
265         This call will return the current time as far as it is already known to the scheduler. If
266         the scheduler is running, this will return eventTime(), otherwise it will return
267         ClockService::now(). While the scheduler is running, this will reduce the number of system
268         calls.
269      */
270     ClockService::clock_type now();
271
272     /** \brief Set watchdog timeout to \a ms milliseconds.
273
274         Setting the watchdog timeout to 0 will disable the watchdog.
275      */
276     void watchdogTimeout(unsigned ms);
277
278     /** \brief Current watchdog timeout in milliseconds */
279     unsigned watchdogTimeout();
280
281     /** \brief Number of watchdog events
282
283         calling watchtogEvents() will reset the counter to 0
284      */
285     unsigned watchdogEvents();
286
287     /** \brief Enable/disable abort on watchdog event.
288
289         Calling watchdogAbort(\c true) will enable aborting the program execution on a watchdog
290         event.
291      */
292     void watchdogAbort(bool flag);
293
294     /** \brief Get current watchdog abort on event status */
295     bool watchdogAbort();
296
297     /** \brief Switch to using hi resolution timers
298
299         By default, timers are implemented directly using epoll. This however restricts the timer
300         resolution to that of the kernel HZ value.
301
302         High resolution timers are implemented either using POSIX timers or, when available, using
303         the Linux special \c timerfd() syscall.
304
305         POSIX timers are delivered using signals. A high timer load this increases the signal load
306         considerably. \c timerfd()'s are delivered on a file descriptor and thus don't have such a
307         scalability issue.
308
309         \warning The timer source must not be switched from a scheduler callback
310      */
311     void hiresTimers();
312
313     /** \brief Switch back to using epoll for timing
314         \see hiresTimers()
315      */
316     void loresTimers();
317
318     /** \brief return \c true, if \c timerfd() timing is available, \c false otherwise
319         \see hiresTimers()
320      */
321     bool haveScalableHiresTimers();
322
323     /** \brief Return \c true, if using hires times, \c false otherwise
324         \see hiresTimers() */
325     bool usingHiresTimers();
326
327     /** \brief Restart scheduler
328
329         This call will restart all scheduler dispatchers (timers, signals, file descriptors). This
330         is necessary after a fork().
331         \warning This call will \e remove all registered events from the scheduler
332      */
333     void restart();
334
335     /** \brief Return \c true, if no event is registered, \c false otherwise. */
336     bool empty();
337
338     /** \brief %scheduler specific time source for Utils/Logger framework
339
340         This time source may be used to provide timing information for log messages within the
341         Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
342         information.
343
344         \code
345         senf::log::timeSource<senf::scheduler::LogTimeSource>();
346         \endcode
347
348         Using this information reduces the number of necessary ClockService::now() calls and thus
349         the number of system calls.
350      */
351     struct LogTimeSource : public senf::log::TimeSource
352     {
353         senf::log::time_type operator()() const;
354     };
355
356     /** \brief Temporarily block all signals
357
358         This class is used to temporarily block all signals in a critical section.
359
360         \code
361         // Begin critical section
362         {
363             senf::scheduler::BlockSignals signalBlocker;
364
365             // critical code executed with all signals blocked
366         }
367         // End critical section
368         \endcode
369
370         You need to take care not to block since even the watchdog timer will be disabled while
371         executing within a critical section.
372      */
373     class BlockSignals
374         : boost::noncopyable
375     {
376     public:
377         BlockSignals(bool initiallyBlocked=true);
378                                         ///< Block signals until end of scope
379                                         /**< \param[in] initiallyBlocked set to \c false to not
380                                              automatically block signals initially */
381         ~BlockSignals();                ///< Release all signal blocks
382
383         void block();                   ///< Block signals if not blocked
384         void unblock();                 ///< Unblock signals if blocked
385         bool blocked() const;           ///< \c true, if signals currently blocked, \c false
386                                         ///< otherwise
387
388     private:
389         bool blocked_;
390         sigset_t allSigs_;
391         sigset_t savedSigs_;
392     };
393
394 }}
395
396 //-/////////////////////////////////////////////////////////////////////////////////////////////////
397 #include "Scheduler.cci"
398 //#include "Scheduler.ct"
399 //#include "Scheduler.cti"
400 #endif
401
402 \f
403 // Local Variables:
404 // mode: c++
405 // fill-column: 100
406 // c-file-style: "senf"
407 // indent-tabs-mode: nil
408 // ispell-local-dictionary: "american"
409 // compile-command: "scons -u test"
410 // comment-column: 40
411 // End: