4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
6 // Stefan Bund <stefan.bund@fokus.fraunhofer.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.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 // Pass 'handle' as additional first argument to callback()
76 Scheduler::instance().add(handle, boost::bind(&callback, handle, _1))
77 // Call timeout() handler with argument 'n'
78 Scheduler::instance().timeout(boost::bind(&timeout, n))
81 To use member-functions as callbacks, use either <a
82 href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a> or senf::membind()
84 // e.g. in Foo::Foo() constructor:
85 Scheduler::instance().add(handle_, senf::membind(&Foo::callback, this))
89 \section sched_fd Registering file descriptors
91 File descriptors are managed using add() or remove()
93 Scheduler::instance().add(handle, &callback);
94 Scheduler::instance().remove(handle);
97 The callback will be called with one additional argument. This argument is the event mask of
98 type EventId. This mask will tell, which of the registered events are signaled. The
99 additional flags EV_HUP or EV_ERR (on hangup or error condition) may be set additionally.
101 Only a single handler may be registered for any combination of file descriptor and event
102 (registering multiple callbacks for a single fd and event does not make sense).
104 The scheduler will accept any object as \a handle argument as long as retrieve_filehandle()
105 may be called on that object
107 int fd = retrieve_filehandle(handle);
109 to fetch the file handle given some abstract handle type. retrieve_filehandle() will be
110 found using ADL depending on the argument namespace. A default implementation is provided
111 for \c int arguments (file descriptors)
114 \section sched_timers Registering timers
116 The Scheduler has very simple timer support. There is only one type of timer: A single-shot
117 deadline timer. More complex timers are built based on this. Timers are managed using
118 timeout() and cancelTimeout()
120 int id = Scheduler::instance().timeout(Scheduler::instance().eventTime() + ClockService::milliseconds(100),
122 Scheduler::instance().cancelTimeout(id);
124 Timing is based on the ClockService, which provides a high resolution and strictly
125 monotonous time source. Registering a timeout will fire the callback when the target time is
126 reached. The timer may be canceled by passing the returned \a id to cancelTimeout().
128 There are two parameters which adjust the exact: \a timeoutEarly and \a timeoutAdjust. \a
129 timeoutEarly is the time, a callback may be called before the deadline time is
130 reached. Setting this value below the scheduling granularity of the kernel will have the
131 scheduler go into a <em>busy wait</em> (that is, an endless loop consuming 100% of CPU
132 recources) until the deadline time is reached! This is seldom desired. The default setting
133 of 11ms is adequate in most cases (it's slightly above the lowest linux scheduling
136 The other timeout scheduling parameter is \a timeoutAdjust. This value will be added to the
137 timeout value before calculating the next delay value thereby compensating for \a
138 timeoutEarly. By default, this value is set to 0 but may be changed if needed.
141 \section sched_signals Registering POSIX/UNIX signals
143 The Scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
144 scheduler will be handled \e synchronously within the event loop.
146 Scheduler::instance().registerSignal(SIGUSR1, &callback);
147 Scheduler::instance().unregisterSignal(SIGUSR1);
149 When registering a signal with the scheduler, that signal will automatically be blocked so
150 it can be handled within the scheduler.
152 A registered signal does \e not count as 'something to do'. It is therefore not possible to
153 wait for signals \e only.
155 \todo Fix EventId parameter (probably to int) to allow |-ing without casting ...
157 \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
165 SENF_LOG_CLASS_AREA();
167 ///////////////////////////////////////////////////////////////////////////
170 /** \brief Types of file descriptor events */
171 enum EventId { EV_NONE=0,
172 EV_READ=1, EV_PRIO=2, EV_WRITE=4,
174 EV_HUP=8, EV_ERR=16 };
176 /** \brief Template typedef for Callback type
178 This is a template typedef (which does not exist in C++) that is, a template class whose
179 sole member is a typedef symbol defining the callback type given the handle type.
181 The Callback is any callable object taking a \c Handle and an \c EventId as argument.
182 template <class Handle>
183 struct GenericCallback {
184 typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
189 typedef boost::function<void (EventId)> FdCallback;
191 /** \brief Callback type for timer events */
192 typedef boost::function<void ()> SimpleCallback;
194 ///////////////////////////////////////////////////////////////////////////
195 ///\name Structors and default members
198 // private default constructor
199 // no copy constructor
200 // no copy assignment
201 // default destructor
202 // no conversion constructors
204 /** \brief Return Scheduler instance
206 This static member is used to access the singleton instance. This member is save to
207 return a correctly initialized Scheduler instance even if called at global construction
210 \implementation This static member just defines the Scheduler as a static method
211 variable. The C++ standard then provides above guarantee. The instance will be
212 initialized the first time, the code flow passes the variable declaration found in
215 static Scheduler & instance();
218 ///////////////////////////////////////////////////////////////////////////
220 ///\name File Descriptors
223 template <class Handle>
224 void add(Handle const & handle, FdCallback const & cb,
225 int eventMask = EV_ALL); ///< Add file handle event callback
226 /**< add() will add a callback to the Scheduler. The
227 callback will be called for the given type of event on
228 the given arbitrary file-descriptor or
229 handle-like object. If there already is a Callback
230 registered for one of the events requested, the new
231 handler will replace the old one.
232 \param[in] handle file descriptor or handle providing
233 the Handle interface defined above.
234 \param[in] cb callback
235 \param[in] eventMask arbitrary combination via '|'
236 operator of EventId designators. */
237 template <class Handle>
238 void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
239 /**< remove() will remove any callback registered for any of
240 the given events on the given file descriptor or handle
242 \param[in] handle file descriptor or handle providing
243 the Handle interface defined above.
244 \param[in] eventMask arbitrary combination via '|'
245 operator of EventId designators. */
252 unsigned timeout(ClockService::clock_type timeout, SimpleCallback const & cb);
253 ///< Add timeout event
254 /**< \param[in] timeout timeout in nanoseconds
255 \param[in] cb callback to call after \a timeout
258 void cancelTimeout(unsigned id); ///< Cancel timeout \a id
260 ClockService::clock_type timeoutEarly() const;
261 ///< Fetch the \a timeoutEarly parameter
262 void timeoutEarly(ClockService::clock_type v);
263 ///< Set the \a timeoutEarly parameter
265 ClockService::clock_type timeoutAdjust() const;\
266 ///< Fetch the \a timeoutAdjust parameter
267 void timeoutAdjust(ClockService::clock_type v);
268 ///< Set the \a timeoutAdjust parameter
272 ///\name Signal handlers
275 void registerSignal(unsigned signal, SimpleCallback const & cb);
276 ///< Add signal handler
277 /**< \param[in] signal signal number to register handler for
278 \param[in] cb callback to call whenever \a signal is
281 void unregisterSignal(unsigned signal);
282 ///< Remove signal handler for \a signal
284 struct InvalidSignalNumberException : public std::exception
285 { virtual char const * what() const throw()
286 { return "senf::Scheduler::InvalidSignalNumberException"; } };
291 void process(); ///< Event handler main loop
292 /**< This member must be called at some time to enter the
293 event handler main loop. Only while this function is
294 running any events are handled. The call will return
295 only, if any callback calls terminate(). */
297 void terminate(); ///< Called by callbacks to terminate the main loop
298 /**< This member may be called by any callback to tell the
299 main loop to terminate. The main loop will return to
300 it's caller after the currently running callback
303 ClockService::clock_type eventTime() const; ///< Return date/time of last event
310 void do_add(int fd, FdCallback const & cb, int eventMask = EV_ALL);
311 void do_remove(int fd, int eventMask = EV_ALL);
313 void registerSigHandlers();
314 static void sigHandler(int signal, ::siginfo_t * siginfo, void *);
318 /** \brief Descriptor event specification
326 EventSpec() : file(false) {}
328 int epollMask() const;
333 /** \brief Timer event specification
337 TimerSpec() : timeout(), cb() {}
338 TimerSpec(ClockService::clock_type timeout_, SimpleCallback cb_, unsigned id_)
339 : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
341 bool operator< (TimerSpec const & other) const
342 { return timeout > other.timeout; }
344 ClockService::clock_type timeout;
352 typedef std::map<int,EventSpec> FdTable;
353 typedef std::map<unsigned,TimerSpec> TimerMap; // sorted by id
357 struct TimerSpecCompare
359 typedef TimerMap::iterator first_argument_type;
360 typedef TimerMap::iterator second_argument_type;
361 typedef bool result_type;
363 result_type operator()(first_argument_type a, second_argument_type b);
368 typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>,
369 TimerSpecCompare> TimerQueue; // sorted by time
371 typedef std::vector<SimpleCallback> SigHandlers;
376 unsigned timerIdCounter_;
377 TimerQueue timerQueue_;
380 SigHandlers sigHandlers_;
386 ClockService::clock_type eventTime_;
387 ClockService::clock_type eventEarly_;
388 ClockService::clock_type eventAdjust_;
391 /** \brief Default file descriptor accessor
393 retrieve_filehandle() provides the Scheduler with support for explicit file descriptors as
394 file handle argument.
398 int retrieve_filehandle(int fd);
400 /** \brief Scheduler specific time source for Utils/Logger framework
402 This time source may be used to provide timing information for log messages within the
403 Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
406 struct SchedulerLogTimeSource : public senf::log::TimeSource
408 boost::posix_time::ptime operator()() const;
413 ///////////////////////////////hh.e////////////////////////////////////////
414 #include "Scheduler.cci"
415 //#include "Scheduler.ct"
416 #include "Scheduler.cti"
423 // c-file-style: "senf"
424 // indent-tabs-mode: nil
425 // ispell-local-dictionary: "american"
426 // compile-command: "scons -u test"
427 // comment-column: 40