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
28 #define HH_Scheduler_ 1
35 #include <boost/function.hpp>
36 #include <boost/utility.hpp>
37 #include <boost/call_traits.hpp>
38 #include <boost/integer.hpp>
39 #include "ClockService.hh"
40 #include "../Utils/Logger/SenfLog.hh"
42 //#include "scheduler.mpp"
43 ///////////////////////////////hh.p////////////////////////////////////////
45 /** \brief SENF Project namespace */
48 /** \brief Singleton class to manage the event loop
50 The %scheduler singleton manages the central event loop. It manages and dispatches all types
51 of events managed by the scheduler library:
52 \li File descriptor notifications
56 The %scheduler is entered by calling it's process() member. This call will continue to run as
57 long as there is something to do, or until one of the handlers calls terminate(). The
58 %scheduler has 'something to do' as long as there is any file descriptor or timeout active.
60 The %scheduler only provides low level primitive scheduling capability. Additional helpers
61 are defined on top of this functionality (e.g. ReadHelper or WriteHelper or the interval
65 \section sched_handlers Specifying handlers
67 All handlers are passed as generic <a
68 href="http://www.boost.org/doc/html/function.html">Boost.Function</a> objects. This allows
69 to pass any callable as a handler. Depending on the type of handler, some additional
70 arguments may be passed to the handler by the %scheduler.
72 If you need to pass additional information to your handler, use <a
73 href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a>:
75 // Handle callback function
76 void callback(UDPv4ClientSocketHandle handle, senf::Scheduler::EventId event) {..}
77 // Pass 'handle' as additional first argument to callback()
78 Scheduler::instance().add(handle, boost::bind(&callback, handle, _1), EV_READ)
80 void timeout( int n) {..}
81 // Call timeout() handler with argument 'n'
82 Scheduler::instance().timeout(boost::bind(&timeout, n))
85 To use member-functions as callbacks, use either <a
86 href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a> or senf::membind()
88 // e.g. in Foo::Foo() constructor:
89 Scheduler::instance().add(handle_, senf::membind(&Foo::callback, this)), EV_READ)
93 \section sched_fd Registering file descriptors
95 File descriptors are managed using add() or remove()
97 Scheduler::instance().add(handle, &callback, EV_ALL);
98 Scheduler::instance().remove(handle);
101 The callback will be called with one additional argument. This argument is the event mask of
102 type EventId. This mask will tell, which of the registered events are signaled. The
103 additional flags EV_HUP or EV_ERR (on hangup or error condition) may be set additionally.
105 Only a single handler may be registered for any combination of file descriptor and event
106 (registering multiple callbacks for a single fd and event does not make sense).
108 The %scheduler will accept any object as \a handle argument as long as retrieve_filehandle()
109 may be called on that object
111 int fd = retrieve_filehandle(handle);
113 to fetch the file handle given some abstract handle type. retrieve_filehandle() will be
114 found using ADL depending on the argument namespace. A default implementation is provided
115 for \c int arguments (file descriptors)
118 \section sched_timers Registering timers
120 The %scheduler has very simple timer support. There is only one type of timer: A single-shot
121 deadline timer. More complex timers are built based on this. Timers are managed using
122 timeout() and cancelTimeout()
124 int id = Scheduler::instance().timeout(Scheduler::instance().eventTime() + ClockService::milliseconds(100),
126 Scheduler::instance().cancelTimeout(id);
128 Timing is based on the ClockService, which provides a high resolution and strictly
129 monotonous time source. Registering a timeout will fire the callback when the target time is
130 reached. The timer may be canceled by passing the returned \a id to cancelTimeout().
132 There are two parameters which adjust the exact: \a timeoutEarly and \a timeoutAdjust. \a
133 timeoutEarly is the time, a callback may be called before the deadline time is
134 reached. Setting this value below the scheduling granularity of the kernel will have the
135 %scheduler go into a <em>busy wait</em> (that is, an endless loop consuming 100% of CPU
136 recources) until the deadline time is reached! This is seldom desired. The default setting
137 of 11ms is adequate in most cases (it's slightly above the lowest linux scheduling
140 The other timeout scheduling parameter is \a timeoutAdjust. This value will be added to the
141 timeout value before calculating the next delay value thereby compensating for \a
142 timeoutEarly. By default, this value is set to 0 but may be changed if needed.
145 \section sched_signals Registering POSIX/UNIX signals
147 The %scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
148 %scheduler will be handled \e synchronously within the event loop.
150 Scheduler::instance().registerSignal(SIGUSR1, &callback);
151 Scheduler::instance().unregisterSignal(SIGUSR1);
153 When registering a signal with the %scheduler, that signal will automatically be blocked so
154 it can be handled within the %scheduler.
156 A registered signal does \e not count as 'something to do'. It is therefore not possible to
157 wait for signals \e only.
159 \todo Fix EventId parameter (probably to int) to allow |-ing without casting ...
161 \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
169 SENF_LOG_CLASS_AREA();
171 ///////////////////////////////////////////////////////////////////////////
174 /** \brief Types of file descriptor events
176 These events are grouped into to classes:
177 \li Ordinary file descriptor events for which handlers may be registered. These are
178 EV_READ, EV_PRIO and EV_WRITE. EV_ALL is a combination of these three.
179 \li Error flags. These additional flags may be passed to a handler to pass an error
180 condition to the handler.
183 EV_NONE = 0 /**< No event */
184 , EV_READ = 1 /**< File descriptor is readable */
185 , EV_PRIO = 2 /**< File descriptor has OOB data */
186 , EV_WRITE = 4 /**< File descriptor is writable */
187 , EV_ALL = 7 /**< Used to register all events at once (read/prio/write) */
188 , EV_HUP = 8 /**< Hangup condition on file handle */
189 , EV_ERR = 16 /**< Error condition on file handle */
192 /** \brief Template typedef for Callback type
194 This is a template typedef (which does not exist in C++) that is, a template class whose
195 sole member is a typedef symbol defining the callback type given the handle type.
197 The Callback is any callable object taking a \c Handle and an \c EventId as argument.
199 template <class Handle>
200 struct GenericCallback {
201 typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
206 typedef boost::function<void (EventId)> FdCallback;
208 /** \brief Callback type for timer events */
209 typedef boost::function<void ()> SimpleCallback;
211 ///////////////////////////////////////////////////////////////////////////
212 ///\name Structors and default members
215 // private default constructor
216 // no copy constructor
217 // no copy assignment
218 // default destructor
219 // no conversion constructors
221 /** \brief Return %scheduler instance
223 This static member is used to access the singleton instance. This member is save to
224 return a correctly initialized %scheduler instance even if called at global construction
227 \implementation This static member just defines the %scheduler as a static method
228 variable. The C++ standard then provides above guarantee. The instance will be
229 initialized the first time, the code flow passes the variable declaration found in
232 static Scheduler & instance();
235 ///////////////////////////////////////////////////////////////////////////
237 ///\name File Descriptors
240 template <class Handle>
241 void add(Handle const & handle, FdCallback const & cb,
242 int eventMask = EV_ALL); ///< Add file handle event callback
243 /**< add() will add a callback to the %scheduler. The
244 callback will be called for the given type of event on
245 the given arbitrary file-descriptor or
246 handle-like object. If there already is a Callback
247 registered for one of the events requested, the new
248 handler will replace the old one.
249 \param[in] handle file descriptor or handle providing
250 the Handle interface defined above.
251 \param[in] cb callback
252 \param[in] eventMask arbitrary combination via '|'
253 operator of \ref senf::Scheduler::EventId "EventId"
255 template <class Handle>
256 void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
257 /**< remove() will remove any callback registered for any of
258 the given events on the given file descriptor or handle
260 \param[in] handle file descriptor or handle providing
261 the Handle interface defined above.
262 \param[in] eventMask arbitrary combination via '|'
263 operator of \ref senf::Scheduler::EventId "EventId"
270 unsigned timeout(ClockService::clock_type timeout, SimpleCallback const & cb);
271 ///< Add timeout event
272 /**< \returns timer id
273 \param[in] timeout timeout in nanoseconds
274 \param[in] cb callback to call after \a timeout
277 void cancelTimeout(unsigned id); ///< Cancel timeout \a id
279 ClockService::clock_type timeoutEarly() const;
280 ///< Fetch the \a timeoutEarly parameter
281 void timeoutEarly(ClockService::clock_type v);
282 ///< Set the \a timeoutEarly parameter
284 ClockService::clock_type timeoutAdjust() const;\
285 ///< Fetch the \a timeoutAdjust parameter
286 void timeoutAdjust(ClockService::clock_type v);
287 ///< Set the \a timeoutAdjust parameter
291 ///\name Signal handlers
294 void registerSignal(unsigned signal, SimpleCallback const & cb);
295 ///< Add signal handler
296 /**< \param[in] signal signal number to register handler for
297 \param[in] cb callback to call whenever \a signal is
300 void unregisterSignal(unsigned signal);
301 ///< Remove signal handler for \a signal
303 /// The signal number passed to registerSignal or unregisterSignal is invalid
304 struct InvalidSignalNumberException : public senf::Exception
305 { InvalidSignalNumberException()
306 : senf::Exception("senf::Scheduler::InvalidSignalNumberException"){} };
311 void process(); ///< Event handler main loop
312 /**< This member must be called at some time to enter the
313 event handler main loop. Only while this function is
314 running any events are handled. The call will return
315 only, if any callback calls terminate(). */
317 void terminate(); ///< Called by callbacks to terminate the main loop
318 /**< This member may be called by any callback to tell the
319 main loop to terminate. The main loop will return to
320 it's caller after the currently running callback
323 ClockService::clock_type eventTime() const; ///< Return date/time of last event
330 void do_add(int fd, FdCallback const & cb, int eventMask = EV_ALL);
331 void do_remove(int fd, int eventMask = EV_ALL);
333 void registerSigHandlers();
334 static void sigHandler(int signal, ::siginfo_t * siginfo, void *);
338 /** \brief Descriptor event specification
346 EventSpec() : file(false) {}
348 int epollMask() const;
353 /** \brief Timer event specification
357 TimerSpec() : timeout(), cb() {}
358 TimerSpec(ClockService::clock_type timeout_, SimpleCallback cb_, unsigned id_)
359 : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
361 bool operator< (TimerSpec const & other) const
362 { return timeout > other.timeout; }
364 ClockService::clock_type timeout;
372 typedef std::map<int,EventSpec> FdTable;
373 typedef std::map<unsigned,TimerSpec> TimerMap; // sorted by id
374 typedef std::vector<unsigned> FdEraseList;
378 struct TimerSpecCompare
380 typedef TimerMap::iterator first_argument_type;
381 typedef TimerMap::iterator second_argument_type;
382 typedef bool result_type;
384 result_type operator()(first_argument_type a, second_argument_type b);
389 typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>,
390 TimerSpecCompare> TimerQueue; // sorted by time
392 typedef std::vector<SimpleCallback> SigHandlers;
395 FdEraseList fdErase_;
398 unsigned timerIdCounter_;
399 TimerQueue timerQueue_;
402 SigHandlers sigHandlers_;
408 ClockService::clock_type eventTime_;
409 ClockService::clock_type eventEarly_;
410 ClockService::clock_type eventAdjust_;
413 /** \brief Default file descriptor accessor
415 retrieve_filehandle() provides the %scheduler with support for explicit file descriptors as
416 file handle argument.
420 int retrieve_filehandle(int fd);
422 /** \brief %scheduler specific time source for Utils/Logger framework
424 This time source may be used to provide timing information for log messages within the
425 Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
428 struct SchedulerLogTimeSource : public senf::log::TimeSource
430 boost::posix_time::ptime operator()() const;
435 ///////////////////////////////hh.e////////////////////////////////////////
436 #include "Scheduler.cci"
437 //#include "Scheduler.ct"
438 #include "Scheduler.cti"
445 // c-file-style: "senf"
446 // indent-tabs-mode: nil
447 // ispell-local-dictionary: "american"
448 // compile-command: "scons -u test"
449 // comment-column: 40