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