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/Target.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
64 \section sched_handlers Handlers
66 All handlers are managed as generic <a
67 href="http://www.boost.org/doc/html/function.html">Boost.Function</a> objects. This allows
68 to pass any callable as a handler. Depending on the type of handler, some additional
69 arguments may be passed to the handler by the scheduler. If you want to pass additional
70 arguments to the handler, use <a
71 href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a>)).
74 \section sched_fd File descriptors
76 File descriptors are managed using add() or remove()
78 Scheduler::instance().add(handle, &callback);
79 Scheduler::instance().remove(handle);
81 The callback will be called with one additional argument. This argument is the event mask of
82 type EventId. This mask will tell, which of the registered events are
83 signaled. Additionally, EV_HUP or EV_ERR on hangup or error condition on the handle.
85 There is always only one handler registered for a file descriptor (registering multiple
86 callbacks for a single fd does not make sense).
88 The scheduler will accept an almost arbitrary object as it's first argument. It will use
90 int fd = retrieve_filehandle(handle);
92 To fetch the file handle given some abstract handle type. The definition of
93 retrieve_filehandle() will be found using ADL.
96 \section sched_timers Timers
98 The Scheduler has very simple timer support. There is only one type of timer: A single-shot
99 deadline timer. More complex timers are built based on this. Timers are managed using
100 timeout() and cancelTimeout()
102 int id = Scheduler::instance().timeout(Scheduler::instance().eventTime() + ClockService::milliseconds(100),
104 Scheduler::instance().cancelTimeout(id);
106 Timing is based on the ClockService, which provides a high resolution and strictly
107 monotonous time source. Registering a timeout will fire the callback when the target time is
108 reached. The timer may be canceled by passing the returned \a id to cancelTimeout().
110 There are two parameters which adjust the exact: \a timeoutEarly and \a timeoutAdjust. \a
111 timeoutEarly is the time, a callback may be called before the deadline time is
112 reached. Setting this value below the scheduling granularity of the kernel will have the
113 scheduler go into a <em>busy wait</em> (that is, an endless loop consuming 100% of CPU
114 recources) until the deadline time is reached! This is seldom desired. The default setting
115 of 11ms is adequate in most cases (it's slightly above the lowest linux scheduling
118 The other timeout scheduling parameter is \a timeoutAdjust. This value will be added to the
119 timeout value before calculating the next delay value thereby compensating for \a
120 timeoutEarly. By default, this value is set to 0 but may be changed if needed.
123 \section sched_signals POSIX/UNIX signals
125 The Scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
126 scheduler will be handled \e synchronously within the event loop.
128 Scheduler::instance().registerSignal(SIGUSR1, &callback);
129 Scheduler::instance().unregisterSignal(SIGUSR1);
131 When registering a signal with the scheduler, that signal will automatically be blocked so
132 it can be handled within the scheduler.
134 A registered signal does \e not count as 'something to do'. It is therefore not possible to
135 wait for signals \e only.
137 \todo Fix EventId parameter (probably to int) to allow |-ing without casting ...
143 ///////////////////////////////////////////////////////////////////////////
146 /** \brief Types of file descriptor events */
147 enum EventId { EV_NONE=0,
148 EV_READ=1, EV_PRIO=2, EV_WRITE=4,
150 EV_HUP=8, EV_ERR=16 };
152 /** \brief Template typedef for Callback type
154 This is a template typedef (which does not exist in C++) that is, a template class whose
155 sole member is a typedef symbol defining the callback type given the handle type.
157 The Callback is any callable object taking a \c Handle and an \c EventId as argument.
158 template <class Handle>
159 struct GenericCallback {
160 typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
165 typedef boost::function<void (EventId)> FdCallback;
167 /** \brief Callback type for timer events */
168 typedef boost::function<void ()> SimpleCallback;
170 ///////////////////////////////////////////////////////////////////////////
171 ///\name Structors and default members
174 // private default constructor
175 // no copy constructor
176 // no copy assignment
177 // default destructor
178 // no conversion constructors
180 /** \brief Return Scheduler instance
182 This static member is used to access the singleton instance. This member is save to
183 return a correctly initialized Scheduler instance even if called at global construction
186 \implementation This static member just defines the Scheduler as a static method
187 variable. The C++ standard then provides above guarantee. The instance will be
188 initialized the first time, the code flow passes the variable declaration found in
191 static Scheduler & instance();
194 ///////////////////////////////////////////////////////////////////////////
196 ///\name File Descriptors
199 template <class Handle>
200 void add(Handle const & handle, FdCallback const & cb,
201 int eventMask = EV_ALL); ///< Add file handle event callback
202 /**< add() will add a callback to the Scheduler. The
203 callback will be called for the given type of event on
204 the given arbitrary file-descriptor or
205 handle-like object. If there already is a Callback
206 registered for one of the events requested, the new
207 handler will replace the old one.
208 \param[in] handle file descriptor or handle providing
209 the Handle interface defined above.
210 \param[in] cb callback
211 \param[in] eventMask arbitrary combination via '|'
212 operator of EventId designators. */
213 template <class Handle>
214 void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
215 /**< remove() will remove any callback registered for any of
216 the given events on the given file descriptor or handle
218 \param[in] handle file descriptor or handle providing
219 the Handle interface defined above.
220 \param[in] eventMask arbitrary combination via '|'
221 operator of EventId designators. */
228 unsigned timeout(ClockService::clock_type timeout, SimpleCallback const & cb);
229 ///< Add timeout event
230 /**< \param[in] timeout timeout in nanoseconds
231 \param[in] cb callback to call after \a timeout
234 void cancelTimeout(unsigned id); ///< Cancel timeout \a id
236 ClockService::clock_type timeoutEarly() const;
237 ///< Fetch the \a timeoutEarly parameter
238 void timeoutEarly(ClockService::clock_type v);
239 ///< Set the \a timeoutEarly parameter
241 ClockService::clock_type timeoutAdjust() const;\
242 ///< Fetch the \a timeoutAdjust parameter
243 void timeoutAdjust(ClockService::clock_type v);
244 ///< Set the \a timeoutAdjust parameter
248 ///\name Signal handlers
251 void registerSignal(unsigned signal, SimpleCallback const & cb);
252 ///< Add signal handler
253 /**< \param[in] signal signal number to register handler for
254 \param[in] cb callback to call whenever \a signal is
257 void unregisterSignal(unsigned signal);
258 ///< Remove signal handler for \a signal
260 struct InvalidSignalNumberException : public std::exception
261 { virtual char const * what() const throw()
262 { return "senf::Scheduler::InvalidSignalNumberException"; } };
267 void process(); ///< Event handler main loop
268 /**< This member must be called at some time to enter the
269 event handler main loop. Only while this function is
270 running any events are handled. The call will return
271 only, if any callback calls terminate(). */
273 void terminate(); ///< Called by callbacks to terminate the main loop
274 /**< This member may be called by any callback to tell the
275 main loop to terminate. The main loop will return to
276 it's caller after the currently running callback
279 ClockService::clock_type eventTime() const; ///< Return date/time of last event
286 void do_add(int fd, FdCallback const & cb, int eventMask = EV_ALL);
287 void do_remove(int fd, int eventMask = EV_ALL);
289 void registerSigHandlers();
290 static void sigHandler(int signal, ::siginfo_t * siginfo, void *);
294 /** \brief Descriptor event specification
302 int epollMask() const;
305 /** \brief Timer event specification
309 TimerSpec() : timeout(), cb() {}
310 TimerSpec(ClockService::clock_type timeout_, SimpleCallback cb_, unsigned id_)
311 : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
313 bool operator< (TimerSpec const & other) const
314 { return timeout > other.timeout; }
316 ClockService::clock_type timeout;
324 typedef std::map<int,EventSpec> FdTable;
325 typedef std::map<unsigned,TimerSpec> TimerMap; // sorted by id
329 struct TimerSpecCompare
331 typedef TimerMap::iterator first_argument_type;
332 typedef TimerMap::iterator second_argument_type;
333 typedef bool result_type;
335 result_type operator()(first_argument_type a, second_argument_type b);
340 typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>,
341 TimerSpecCompare> TimerQueue; // sorted by time
343 typedef std::vector<SimpleCallback> SigHandlers;
347 unsigned timerIdCounter_;
348 TimerQueue timerQueue_;
351 SigHandlers sigHandlers_;
357 ClockService::clock_type eventTime_;
358 ClockService::clock_type eventEarly_;
359 ClockService::clock_type eventAdjust_;
362 /** \brief Default file descriptor accessor
364 retrieve_filehandle() provides the Scheduler with support for explicit file descriptors as
365 file handle argument.
369 int retrieve_filehandle(int fd);
371 /** \brief Scheduler specific time source for Utils/Logger framework
373 This time source may be used to provide timing information for log messages within the
374 Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
377 struct SchedulerLogTimeSource : public senf::log::TimeSource
379 boost::posix_time::ptime operator()() const;
384 ///////////////////////////////hh.e////////////////////////////////////////
385 #include "Scheduler.cci"
386 //#include "Scheduler.ct"
387 #include "Scheduler.cti"
394 // c-file-style: "senf"
395 // indent-tabs-mode: nil
396 // ispell-local-dictionary: "american"
397 // compile-command: "scons -u test"
398 // comment-column: 40