4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 // Stefan Bund <g0dil@berlios.de>
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.
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.
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.
24 \brief Scheduler public header
27 #ifndef HH_SENF_Scheduler_Scheduler_
28 #define HH_SENF_Scheduler_Scheduler_ 1
31 #include <boost/utility.hpp>
32 #include <senf/Utils/Logger/TimeSource.hh>
34 #include "TimerEvent.hh"
35 #include "SignalEvent.hh"
36 #include "IdleEvent.hh"
37 #include "EventHook.hh"
39 //#include "scheduler.mpp"
40 ///////////////////////////////hh.p////////////////////////////////////////
44 /** \brief The Scheduler interface
46 The %scheduler API is comprised of two parts:
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
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.
58 \section sched_objects Event classes
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 resposible for it's creation.
65 Every event registration is represented by an instance of an event specific class:
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
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.
78 SomeSocketHandle handle_;
79 senf::scheduler::FdEvent event_;
82 SomeServer(SomeSocketHandle handle)
84 event_ ("SomeServer handler", senf::membind(&SomeServer::readData, this),
85 handle, senf::scheduler::FdEvent::EV_READ)
88 void readData(int events)
90 // read data from handle_, check for eof and so on.
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.
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.
105 \section sched_handlers Specifying handlers
107 All handlers are specified as generic <a
108 href="http://www.boost.org/doc/html/function.html">Boost.Function</a> objects. This allows to
109 pass any callable as a handler. Depending on the type of handler, some additional arguments may
110 be passed to the handler by the %scheduler.
112 If you need to pass additional information to your handler, use <a
113 href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a>:
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);
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));
127 To use member-functions as callbacks, use either <a
128 href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a> or senf::membind()
130 // e.g. in Foo::Foo() constructor:
133 readevent_ ("Foo read", senf::membind(&Foo::callback, this),
134 handle_, senf::scheduler::FdEvent::EV_READ)
138 The handler is identified by an arbitrary, user specified name. This name is used in error
139 messages to identify the failing handler.
142 \section sched_exec Executing the Scheduler
144 To enter the scheduler main-loop, call
147 senf::scheduler::process();
150 This call will only return in two cases:
152 \li When a handler calls senf::scheduler::terminate()
153 \li When there is no active file descriptor or timer event.
155 Additional <a href="#autotoc-7.">generic functions</a> provide information and %scheduler
158 \section sched_container Event objects and container classes
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:
164 #include <boost/ptr_container/ptr_map.hpp>
165 #include <boost/bind.hpp>
174 new senf::scheduler::FdEvent("foo", boost::bind(&callback, this, fd, _1), fd,
175 senf::scheduler::FdEvent::EV_READ) );
178 void callback(int fd, int events)
180 FdEvent & event (fdEvents_[fd]);
189 boost::ptr_map<int, FdEvent> fdEvents_;
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/1_36_0/libs/ptr_container/doc/ptr_container.html">Boost.PointerContainer</a>
198 for the pointer container library reference.
201 \section sched_signals Signals and the Watchdog
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.
209 The watchdog is controlled using the watchdogTimeout(), watchdogEvents() and watchdogAbort().
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
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 ...)
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.
225 \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
228 namespace scheduler {
230 /** \brief Event handler main loop
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.
239 /** \brief \c true, if scheduler is running, \c false otherwise */
242 /** \brief Called by callbacks to terminate the main loop
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.
249 /** \brief Immediately rescheduler
251 Calling yield() will cause the scheduler to terminate the current queue run and immediately
252 rescheduler all pending tasks.
256 /** \brief Return timestamp of last event
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).
261 ClockService::clock_type eventTime();
263 /** \brief Return (approximate) current time
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
270 ClockService::clock_type now();
272 /** \brief Set watchdog timeout to \a ms milliseconds.
274 Setting the watchdog timeout to 0 will disable the watchdog.
276 void watchdogTimeout(unsigned ms);
278 /** \brief Current watchdog timeout in milliseconds */
279 unsigned watchdogTimeout();
281 /** \brief Number of watchdog events
283 calling watchtogEvents() will reset the counter to 0
285 unsigned watchdogEvents();
287 /** \brief Enable/disable abort on watchdog event.
289 Calling watchdogAbort(\c true) will enable aborting the program execution on a watchdog
292 void watchdogAbort(bool flag);
294 /** \brief Get current watchdog abort on event status */
295 bool watchdogAbort();
297 /** \brief Switch to using hi resolution timers
299 By default, timers are implemented directly using epoll. This however restricts the timer
300 resolution to that of the kernel HZ value.
302 High resolution timers are implemented either using POSIX timers or, when available, using
303 the Linux special \c timerfd() syscall.
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
309 \warning The timer source must not be switched from a scheduler callback
313 /** \brief Switch back to using epoll for timing
318 /** \brief return \c true, if \c timerfd() timing is available, \c false otherwise
321 bool haveScalableHiresTimers();
323 /** \brief Return \c true, if using hires times, \c false otherwise
324 \see hiresTimers() */
325 bool usingHiresTimers();
327 /** \brief Restart scheduler
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
335 /** \brief Return \c true, if no event is registered, \c false otherwise. */
338 /** \brief %scheduler specific time source for Utils/Logger framework
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
345 senf::log::timeSource<senf::scheduler::LogTimeSource>();
348 Using this information reduces the number of necessary ClockService::now() calls and thus
349 the number of system calls.
351 struct LogTimeSource : public senf::log::TimeSource
353 senf::log::time_type operator()() const;
356 /** \brief Temporarily block all signals
358 This class is used to temporarily block all signals in a critical section.
361 // Begin critical section
363 senf::scheduler::BlockSignals signalBlocker;
365 // critical code executed with all signals blocked
367 // End critical section
370 You need to take care not to block since even the watchdog timer will be disabled while
371 executing within a critical section.
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
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
396 ///////////////////////////////hh.e////////////////////////////////////////
397 #include "Scheduler.cci"
398 //#include "Scheduler.ct"
399 //#include "Scheduler.cti"
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