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