4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
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
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.
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.
19 // The Original Code is Fraunhofer FOKUS code.
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.
26 // Stefan Bund <g0dil@berlios.de>
29 \brief Scheduler public header
32 #ifndef HH_SENF_Scheduler_Scheduler_
33 #define HH_SENF_Scheduler_Scheduler_ 1
36 #include <boost/utility.hpp>
37 #include <senf/Utils/Logger/TimeSource.hh>
39 #include "TimerEvent.hh"
40 #include "SignalEvent.hh"
41 #include "IdleEvent.hh"
42 #include "EventHook.hh"
44 //#include "scheduler.mpp"
45 //-/////////////////////////////////////////////////////////////////////////////////////////////////
49 /** \brief The Scheduler interface
51 The %scheduler API is comprised of two parts:
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
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.
63 \section sched_objects Event classes
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.
70 Every event registration is represented by an instance of an event specific class:
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
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.
83 SomeSocketHandle handle_;
84 senf::scheduler::FdEvent event_;
87 SomeServer(SomeSocketHandle handle)
89 event_ ("SomeServer handler", senf::membind(&SomeServer::readData, this),
90 handle, senf::scheduler::FdEvent::EV_READ)
93 void readData(int events)
95 // read data from handle_, check for eof and so on.
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.
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.
110 \section sched_handlers Specifying handlers
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.
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>:
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);
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));
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()
135 // e.g. in Foo::Foo() constructor:
138 readevent_ ("Foo read", senf::membind(&Foo::callback, this),
139 handle_, senf::scheduler::FdEvent::EV_READ)
143 The handler is identified by an arbitrary, user specified name. This name is used in error
144 messages to identify the failing handler.
147 \section sched_exec Executing the Scheduler
149 To enter the %scheduler main-loop, call
152 senf::scheduler::process();
155 This call will only return in two cases:
157 \li When a handler calls senf::scheduler::terminate()
158 \li When there is no active file descriptor or timer event.
160 Additional <a href="#autotoc-7.">generic functions</a> provide information and %scheduler
163 \section sched_container Event objects and container classes
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:
169 #include <boost/ptr_container/ptr_map.hpp>
170 #include <boost/bind.hpp>
179 new senf::scheduler::FdEvent("foo", boost::bind(&callback, this, fd, _1), fd,
180 senf::scheduler::FdEvent::EV_READ) );
183 void callback(int fd, int events)
185 FdEvent & event (fdEvents_[fd]);
194 boost::ptr_map<int, FdEvent> fdEvents_;
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.
206 \section sched_signals Signals and the Watchdog
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.
214 The watchdog is controlled using the watchdogTimeout(), watchdogEvents() and watchdogAbort().
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
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 ...)
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.
230 \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
233 namespace scheduler {
235 /** \brief Event handler main loop
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.
244 /** \brief \c true, if scheduler is running, \c false otherwise */
247 /** \brief Called by callbacks to terminate the main loop
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.
254 /** \brief Immediately rescheduler
256 Calling yield() will cause the scheduler to terminate the current queue run and immediately
257 rescheduler all pending tasks.
261 /** \brief Return timestamp of last event
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).
266 ClockService::clock_type eventTime();
268 /** \brief Return (approximate) current time
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
275 ClockService::clock_type now();
277 /** \brief Set watchdog timeout to \a ms milliseconds.
279 Setting the watchdog timeout to 0 will disable the watchdog.
281 void watchdogTimeout(unsigned ms);
283 /** \brief Current watchdog timeout in milliseconds */
284 unsigned watchdogTimeout();
286 /** \brief Number of watchdog events
288 calling watchtogEvents() will reset the counter to 0
290 unsigned watchdogEvents();
292 /** \brief Enable/disable abort on watchdog event.
294 Calling watchdogAbort(\c true) will enable aborting the program execution on a watchdog
297 void watchdogAbort(bool flag);
299 /** \brief Get current watchdog abort on event status */
300 bool watchdogAbort();
302 /** \brief Switch to using hi resolution timers
304 By default, timers are implemented directly using epoll. This however restricts the timer
305 resolution to that of the kernel HZ value.
307 High resolution timers are implemented either using POSIX timers or, when available, using
308 the Linux special \c timerfd() syscall.
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
314 \warning The timer source must not be switched from a scheduler callback
318 /** \brief Switch back to using epoll for timing
323 /** \brief return \c true, if \c timerfd() timing is available, \c false otherwise
326 bool haveScalableHiresTimers();
328 /** \brief Return \c true, if using hires times, \c false otherwise
329 \see hiresTimers() */
330 bool usingHiresTimers();
332 /** \brief Restart scheduler
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
340 /** \brief Return \c true, if no event is registered, \c false otherwise. */
343 /** \brief %scheduler specific time source for Utils/Logger framework
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
350 senf::log::timeSource<senf::scheduler::LogTimeSource>();
353 Using this information reduces the number of necessary ClockService::now() calls and thus
354 the number of system calls.
356 struct LogTimeSource : public senf::log::TimeSource
358 senf::log::time_type operator()() const;
361 /** \brief Temporarily block all signals
363 This class is used to temporarily block all signals in a critical section.
366 // Begin critical section
368 senf::scheduler::BlockSignals signalBlocker;
370 // critical code executed with all signals blocked
372 // End critical section
375 You need to take care not to block since even the watchdog timer will be disabled while
376 executing within a critical section.
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
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
401 //-/////////////////////////////////////////////////////////////////////////////////////////////////
402 #include "Scheduler.cci"
403 //#include "Scheduler.ct"
404 //#include "Scheduler.cti"
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