7a958e38bbc42abf22295f0b7f99743cefd154e1
[senf.git] / Scheduler / Scheduler.hh
1 // $Id$
2 //
3 // Copyright (C) 2006
4 // Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
5 // Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
6 //     Stefan Bund <stefan.bund@fokus.fraunhofer.de>
7 //
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.
12 //
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.
17 //
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.
22
23 /** \file
24     \brief Scheduler public header
25  */
26
27 #ifndef HH_Scheduler_
28 #define HH_Scheduler_ 1
29
30 // Custom includes
31 #include <signal.h>
32 #include <setjmp.h>
33 #include <map>
34 #include <queue>
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"
41
42 //#include "scheduler.mpp"
43 ///////////////////////////////hh.p////////////////////////////////////////
44
45 /** \brief SENF Project namespace */
46 namespace senf {
47
48     /** \brief Singleton class to manage the event loop
49
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
53         \li Timeouts
54         \li UNIX Signals
55
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.
59
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
62         timers of the PPI).
63
64         \section sched_handlers Handlers
65
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>)).
72         
73
74         \section sched_fd File descriptors
75         
76         File descriptors are managed using add() or remove()
77         \code
78         Scheduler::instance().add(handle, &callback);
79         Scheduler::instance().remove(handle);
80         \endcode
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.
84
85         There is always only one handler registered for a file descriptor (registering multiple
86         callbacks for a single fd does not make sense).
87
88         The scheduler will accept an almost arbitrary object as it's first argument. It will use
89         \code
90         int fd = retrieve_filehandle(handle);
91         \endcode
92         To fetch the file handle given some abstract handle type. The definition of
93         retrieve_filehandle() will be found using ADL.
94
95
96         \section sched_timers Timers
97
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()
101         \code
102         int id = Scheduler::instance().timeout(Scheduler::instance().eventTime() + ClockService::milliseconds(100),
103                                                &callback);
104         Scheduler::instance().cancelTimeout(id);
105         \endcode 
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().
109
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
116         granularity). 
117
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.
121
122
123         \section sched_signals POSIX/UNIX signals
124
125         The Scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
126         scheduler will be handled \e synchronously within the event loop.
127         \code
128         Scheduler::instance().registerSignal(SIGUSR1, &callback);
129         Scheduler::instance().unregisterSignal(SIGUSR1);
130         \endcode
131         When registering a signal with the scheduler, that signal will automatically be blocked so
132         it can be handled within the scheduler. 
133
134         A registered signal does \e not count as 'something to do'. It is therefore not possible to
135         wait for signals \e only.
136
137         \todo Fix EventId parameter (probably to int) to allow |-ing without casting ...
138       */
139     class Scheduler
140         : boost::noncopyable
141     {
142     public:
143         ///////////////////////////////////////////////////////////////////////////
144         // Types
145
146         /** \brief Types of file descriptor events */
147         enum EventId { EV_NONE=0,
148                        EV_READ=1, EV_PRIO=2, EV_WRITE=4, 
149                        EV_ALL=7,
150                        EV_HUP=8, EV_ERR=16 };
151
152         /** \brief Template typedef for Callback type
153
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.
156
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,
161                                           EventId) > Callback;
162         };
163          */
164
165         typedef boost::function<void (EventId)> FdCallback;
166
167         /** \brief Callback type for timer events */
168         typedef boost::function<void ()> SimpleCallback;
169
170         ///////////////////////////////////////////////////////////////////////////
171         ///\name Structors and default members
172         ///@{
173
174         // private default constructor
175         // no copy constructor
176         // no copy assignment
177         // default destructor
178         // no conversion constructors
179
180         /** \brief Return Scheduler instance
181
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
184             time
185
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
189                 the instance() body.
190          */
191         static Scheduler & instance();
192
193         ///@}
194         ///////////////////////////////////////////////////////////////////////////
195
196         ///\name File Descriptors
197         ///\{
198
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
217                                              like object.
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. */
222
223         ///\}
224
225         ///\name Timeouts
226         ///\{
227
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
232                                                  milliseconds */
233
234         void cancelTimeout(unsigned id); ///< Cancel timeout \a id
235
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
240
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
245
246         ///\}
247
248         ///\name Signal handlers
249         ///\{
250         
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
255                                                  delivered. */
256
257         void unregisterSignal(unsigned signal);
258                                         ///< Remove signal handler for \a signal
259
260         struct InvalidSignalNumberException : public std::exception
261         { virtual char const * what() const throw() 
262                 { return "senf::Scheduler::InvalidSignalNumberException"; } };
263
264
265         ///\}
266
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(). */
272
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
277                                              returns. */
278         
279         ClockService::clock_type eventTime() const; ///< Return date/time of last event
280
281     protected:
282
283     private:
284         Scheduler();
285
286         void do_add(int fd, FdCallback const & cb, int eventMask = EV_ALL);
287         void do_remove(int fd, int eventMask = EV_ALL);
288
289         void registerSigHandlers();
290         static void sigHandler(int signal, ::siginfo_t * siginfo, void *);
291
292 #       ifndef DOXYGEN
293
294         /** \brief Descriptor event specification
295             \internal */
296         struct EventSpec
297         {
298             FdCallback cb_read;
299             FdCallback cb_prio;
300             FdCallback cb_write;
301
302             int epollMask() const;
303         };
304
305         /** \brief Timer event specification
306             \internal */
307         struct TimerSpec
308         {
309             TimerSpec() : timeout(), cb() {}
310             TimerSpec(ClockService::clock_type timeout_, SimpleCallback cb_, unsigned id_)
311                 : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
312
313             bool operator< (TimerSpec const & other) const
314                 { return timeout > other.timeout; }
315
316             ClockService::clock_type timeout;
317             SimpleCallback cb;
318             unsigned id;
319             bool canceled;
320         };
321
322 #       endif 
323
324         typedef std::map<int,EventSpec> FdTable;
325         typedef std::map<unsigned,TimerSpec> TimerMap; // sorted by id
326
327 #       ifndef DOXYGEN
328
329         struct TimerSpecCompare
330         {
331             typedef TimerMap::iterator first_argument_type;
332             typedef TimerMap::iterator second_argument_type;
333             typedef bool result_type;
334             
335             result_type operator()(first_argument_type a, second_argument_type b);
336         };
337
338 #       endif
339
340         typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>, 
341                                     TimerSpecCompare> TimerQueue; // sorted by time
342
343         typedef std::vector<SimpleCallback> SigHandlers;
344
345         FdTable fdTable_;
346
347         unsigned timerIdCounter_;
348         TimerQueue timerQueue_;
349         TimerMap timerMap_;
350
351         SigHandlers sigHandlers_;
352         ::sigset_t sigset_;
353         int sigpipe_[2];
354
355         int epollFd_;
356         bool terminate_;
357         ClockService::clock_type eventTime_;
358         ClockService::clock_type eventEarly_;
359         ClockService::clock_type eventAdjust_;
360     };
361
362     /** \brief Default file descriptor accessor
363
364         retrieve_filehandle() provides the Scheduler with support for explicit file descriptors as
365         file handle argument.
366
367         \relates Scheduler
368      */
369     int retrieve_filehandle(int fd);
370
371     /** \brief Scheduler specific time source for Utils/Logger framework
372
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
375         information.
376      */
377     struct SchedulerLogTimeSource : public senf::log::TimeSource
378     {
379         boost::posix_time::ptime operator()() const;
380     };
381
382 }
383
384 ///////////////////////////////hh.e////////////////////////////////////////
385 #include "Scheduler.cci"
386 //#include "Scheduler.ct"
387 #include "Scheduler.cti"
388 #endif
389
390 \f
391 // Local Variables:
392 // mode: c++
393 // fill-column: 100
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
399 // End: