695e9b393203242977aa5c048a34b269c34f9f1b
[senf.git] / Scheduler / Scheduler.hh
1 // $Id$
2 //
3 // Copyright (C) 2006
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.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 <map>
33 #include <queue>
34 #include <boost/function.hpp>
35 #include <boost/utility.hpp>
36 #include <boost/call_traits.hpp>
37 #include <boost/integer.hpp>
38 #include "ClockService.hh"
39 #include "../Utils/Logger/SenfLog.hh"
40
41 //#include "scheduler.mpp"
42 ///////////////////////////////hh.p////////////////////////////////////////
43
44 /** \brief SENF Project namespace */
45 namespace senf {
46
47     /** \brief Singleton class to manage the event loop
48
49         The %scheduler singleton manages the central event loop. It manages and dispatches all types
50         of events managed by the scheduler library:
51         \li File descriptor notifications
52         \li Timeouts
53         \li UNIX Signals
54
55         The %scheduler is entered by calling it's process() member. This call will continue to run as
56         long as there is something to do, or until one of the handlers calls terminate(). The
57         %scheduler has 'something to do' as long as there is any file descriptor or timeout active.
58
59         The %scheduler only provides low level primitive scheduling capability. Additional helpers
60         are defined on top of this functionality (e.g. ReadHelper or WriteHelper or the interval
61         timers of the PPI).
62
63
64         \section sched_handlers Specifying handlers
65
66         All handlers are passed 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. 
70
71         If you need to pass additional information to your handler, use <a
72         href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a>:
73         \code
74         // Handle callback function
75         void callback(UDPv4ClientSocketHandle handle, senf::Scheduler::EventId event) {..}
76         // Pass 'handle' as additional first argument to callback()
77         Scheduler::instance().add(handle, boost::bind(&callback, handle, _1), EV_READ)
78          // Timeout function
79         void timeout( int n) {..}
80         // Call timeout() handler with argument 'n'
81         Scheduler::instance().timeout(boost::bind(&timeout, n))
82         \endcode
83
84         To use member-functions as callbacks, use either <a
85         href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a> or senf::membind()
86         \code
87         // e.g. in Foo::Foo() constructor:
88         Scheduler::instance().add(handle_, senf::membind(&Foo::callback, this)), EV_READ)
89         \endcode
90         
91
92         \section sched_fd Registering file descriptors
93         
94         File descriptors are managed using add() or remove()
95         \code
96         Scheduler::instance().add(handle, &callback, EV_ALL);
97         Scheduler::instance().remove(handle);
98         \endcode 
99
100         The callback will be called with one additional argument. This argument is the event mask of
101         type EventId. This mask will tell, which of the registered events are signaled. The
102         additional flags EV_HUP or EV_ERR (on hangup or error condition) may be set additionally.
103
104         Only a single handler may be registered for any combination of file descriptor and event
105         (registering multiple callbacks for a single fd and event does not make sense).
106
107         The %scheduler will accept any object as \a handle argument as long as retrieve_filehandle()
108         may be called on that object
109         \code
110         int fd = retrieve_filehandle(handle);
111         \endcode 
112         to fetch the file handle given some abstract handle type. retrieve_filehandle() will be
113         found using ADL depending on the argument namespace. A default implementation is provided
114         for \c int arguments (file descriptors)
115
116
117         \section sched_timers Registering timers
118
119         The %scheduler has very simple timer support. There is only one type of timer: A single-shot
120         deadline timer. More complex timers are built based on this. Timers are managed using
121         timeout() and cancelTimeout()
122         \code
123         int id = Scheduler::instance().timeout(Scheduler::instance().eventTime() + ClockService::milliseconds(100),
124                                                &callback);
125         Scheduler::instance().cancelTimeout(id);
126         \endcode 
127         Timing is based on the ClockService, which provides a high resolution and strictly
128         monotonous time source. Registering a timeout will fire the callback when the target time is
129         reached. The timer may be canceled by passing the returned \a id to cancelTimeout().
130
131         There are two parameters which adjust the exact: \a timeoutEarly and \a timeoutAdjust. \a
132         timeoutEarly is the time, a callback may be called before the deadline time is
133         reached. Setting this value below the scheduling granularity of the kernel will have the
134         %scheduler go into a <em>busy wait</em> (that is, an endless loop consuming 100% of CPU
135         recources) until the deadline time is reached! This is seldom desired. The default setting
136         of 11ms is adequate in most cases (it's slightly above the lowest linux scheduling
137         granularity). 
138
139         The other timeout scheduling parameter is \a timeoutAdjust. This value will be added to the
140         timeout value before calculating the next delay value thereby compensating for \a
141         timeoutEarly. By default, this value is set to 0 but may be changed if needed.
142
143
144         \section sched_signals Registering POSIX/UNIX signals
145
146         The %scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
147         %scheduler will be handled \e synchronously within the event loop.
148         \code
149         Scheduler::instance().registerSignal(SIGUSR1, &callback);
150         Scheduler::instance().unregisterSignal(SIGUSR1);
151         \endcode
152         When registering a signal with the %scheduler, that signal will automatically be blocked so
153         it can be handled within the %scheduler. 
154
155         A registered signal does \e not count as 'something to do'. It is therefore not possible to
156         wait for signals \e only.
157
158         \todo Fix EventId parameter (probably to int) to allow |-ing without casting ...
159         
160         \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
161             over e.g. NFS.
162
163         \todo Add a check in the alarm callback which is already called every x seconds to check,
164             that a single callback is not blocking.
165       */
166     class Scheduler
167         : boost::noncopyable
168     {
169     public:
170
171         SENF_LOG_CLASS_AREA();
172
173         ///////////////////////////////////////////////////////////////////////////
174         // Types
175
176         /** \brief Types of file descriptor events 
177
178             These events are grouped into to classes:
179             \li Ordinary file descriptor events for which handlers may be registered. These are
180                 EV_READ, EV_PRIO and EV_WRITE. EV_ALL is a combination of these three.
181             \li Error flags. These additional flags may be passed to a handler to pass an error
182                 condition to the handler. 
183          */
184         enum EventId { 
185             EV_NONE  =  0   /**< No event */
186           , EV_READ  =  1   /**< File descriptor is readable */
187           , EV_PRIO  =  2   /**< File descriptor has OOB data */
188           , EV_WRITE =  4   /**< File descriptor is writable */
189           , EV_ALL   =  7   /**< Used to register all events at once (read/prio/write) */
190           , EV_HUP   =  8   /**< Hangup condition on file handle */
191           , EV_ERR   = 16   /**< Error condition on file handle */
192         };
193
194         /** \brief Template typedef for Callback type
195
196             This is a template typedef (which does not exist in C++) that is, a template class whose
197             sole member is a typedef symbol defining the callback type given the handle type.
198
199             The Callback is any callable object taking a \c Handle and an \c EventId as argument.
200             \code
201             template <class Handle>
202             struct GenericCallback {
203                 typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
204                                               EventId) > Callback;
205             };
206             \endcode
207          */
208         typedef boost::function<void (EventId)> FdCallback;
209
210         /** \brief Callback type for timer events */
211         typedef boost::function<void ()> SimpleCallback;
212
213         ///////////////////////////////////////////////////////////////////////////
214         ///\name Structors and default members
215         ///@{
216
217         // private default constructor
218         // no copy constructor
219         // no copy assignment
220         // default destructor
221         // no conversion constructors
222
223         /** \brief Return %scheduler instance
224
225             This static member is used to access the singleton instance. This member is save to
226             return a correctly initialized %scheduler instance even if called at global construction
227             time
228
229             \implementation This static member just defines the %scheduler as a static method
230                 variable. The C++ standard then provides above guarantee. The instance will be
231                 initialized the first time, the code flow passes the variable declaration found in
232                 the instance() body.
233          */
234         static Scheduler & instance();
235
236         ///@}
237         ///////////////////////////////////////////////////////////////////////////
238
239         ///\name File Descriptors
240         ///\{
241
242         template <class Handle>
243         void add(Handle const & handle, FdCallback const & cb,
244                  int eventMask = EV_ALL); ///< Add file handle event callback
245                                         /**< add() will add a callback to the %scheduler. The
246                                              callback will be called for the given type of event on
247                                              the given  arbitrary file-descriptor or
248                                              handle-like object. If there already is a Callback
249                                              registered for one of the events requested, the new
250                                              handler will replace the old one.
251                                              \param[in] handle file descriptor or handle providing
252                                                  the Handle interface defined above.
253                                              \param[in] cb callback
254                                              \param[in] eventMask arbitrary combination via '|'
255                                                  operator of \ref senf::Scheduler::EventId "EventId"
256                                                  designators. */
257         template <class Handle>
258         void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
259                                         /**< remove() will remove any callback registered for any of
260                                              the given events on the given file descriptor or handle
261                                              like object.
262                                              \param[in] handle file descriptor or handle providing
263                                                  the Handle interface defined above.
264                                              \param[in] eventMask arbitrary combination via '|'
265                                                  operator of \ref senf::Scheduler::EventId "EventId"
266                                                  designators. */
267         ///\}
268
269         ///\name Timeouts
270         ///\{
271
272         unsigned timeout(ClockService::clock_type timeout, SimpleCallback const & cb); 
273                                         ///< Add timeout event
274                                         /**< \returns timer id
275                                              \param[in] timeout timeout in nanoseconds
276                                              \param[in] cb callback to call after \a timeout
277                                                  milliseconds */
278
279         void cancelTimeout(unsigned id); ///< Cancel timeout \a id
280
281         ClockService::clock_type timeoutEarly() const;
282                                         ///< Fetch the \a timeoutEarly parameter
283         void timeoutEarly(ClockService::clock_type v);
284                                         ///< Set the \a timeoutEarly parameter
285
286         ClockService::clock_type timeoutAdjust() const;
287                                         ///< Fetch the \a timeoutAdjust parameter
288         void timeoutAdjust(ClockService::clock_type v);
289                                         ///< Set the \a timeoutAdjust parameter
290
291         ///\}
292
293         ///\name Signal handlers
294         ///\{
295         
296         void registerSignal(unsigned signal, SimpleCallback const & cb);
297                                         ///< Add signal handler
298                                         /**< \param[in] signal signal number to register handler for
299                                              \param[in] cb callback to call whenever \a signal is
300                                                  delivered. */
301
302         void unregisterSignal(unsigned signal);
303                                         ///< Remove signal handler for \a signal
304
305         /// The signal number passed to registerSignal or unregisterSignal is invalid
306         struct InvalidSignalNumberException : public senf::Exception
307         { InvalidSignalNumberException() 
308               : senf::Exception("senf::Scheduler::InvalidSignalNumberException"){} };
309
310
311         ///\}
312
313         void process();                 ///< Event handler main loop
314                                         /**< This member must be called at some time to enter the
315                                              event handler main loop. Only while this function is
316                                              running any events are handled. The call will return
317                                              only, if any callback calls terminate(). */
318
319         void terminate();               ///< Called by callbacks to terminate the main loop
320                                         /**< This member may be called by any callback to tell the
321                                              main loop to terminate. The main loop will return to
322                                              it's caller after the currently running callback
323                                              returns. */
324         
325         ClockService::clock_type eventTime() const; ///< Return date/time of last event
326                                         /**< This is the timestamp, the last event has been
327                                              signaled. This is the real time at which the event is
328                                              delivered \e not the time it should have been delivered
329                                              (in the case of timers). */
330
331     protected:
332
333     private:
334         Scheduler();
335
336         void do_add(int fd, FdCallback const & cb, int eventMask = EV_ALL);
337         void do_remove(int fd, int eventMask = EV_ALL);
338
339         void registerSigHandlers();
340         static void sigHandler(int signal, ::siginfo_t * siginfo, void *);
341
342 #       ifndef DOXYGEN
343
344         /** \brief Descriptor event specification
345             \internal */
346         struct EventSpec
347         {
348             FdCallback cb_read;
349             FdCallback cb_prio;
350             FdCallback cb_write;
351
352             EventSpec() : file(false) {}
353
354             int epollMask() const;
355
356             bool file;
357         };
358
359         /** \brief Timer event specification
360             \internal */
361         struct TimerSpec
362         {
363             TimerSpec() : timeout(), cb() {}
364             TimerSpec(ClockService::clock_type timeout_, SimpleCallback cb_, unsigned id_)
365                 : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
366
367             bool operator< (TimerSpec const & other) const
368                 { return timeout > other.timeout; }
369
370             ClockService::clock_type timeout;
371             SimpleCallback cb;
372             unsigned id;
373             bool canceled;
374         };
375
376 #       endif 
377
378         typedef std::map<int,EventSpec> FdTable;
379         typedef std::map<unsigned,TimerSpec> TimerMap; // sorted by id
380         typedef std::vector<unsigned> FdEraseList;
381
382 #       ifndef DOXYGEN
383
384         struct TimerSpecCompare
385         {
386             typedef TimerMap::iterator first_argument_type;
387             typedef TimerMap::iterator second_argument_type;
388             typedef bool result_type;
389             
390             result_type operator()(first_argument_type a, second_argument_type b);
391         };
392
393 #       endif
394
395         typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>, 
396                                     TimerSpecCompare> TimerQueue; // sorted by time
397
398         typedef std::vector<SimpleCallback> SigHandlers;
399
400         FdTable fdTable_;
401         FdEraseList fdErase_;
402         unsigned files_;
403
404         unsigned timerIdCounter_;
405         TimerQueue timerQueue_;
406         TimerMap timerMap_;
407
408         SigHandlers sigHandlers_;
409         ::sigset_t sigset_;
410         int sigpipe_[2];
411
412         int epollFd_;
413         bool terminate_;
414         ClockService::clock_type eventTime_;
415         ClockService::clock_type eventEarly_;
416         ClockService::clock_type eventAdjust_;
417     };
418
419     /** \brief Default file descriptor accessor
420
421         retrieve_filehandle() provides the %scheduler with support for explicit file descriptors as
422         file handle argument.
423
424         \relates Scheduler
425      */
426     int retrieve_filehandle(int fd);
427
428     /** \brief %scheduler specific time source for Utils/Logger framework
429
430         This time source may be used to provide timing information for log messages within the
431         Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
432         information.
433      */
434     struct SchedulerLogTimeSource : public senf::log::TimeSource
435     {
436         senf::log::time_type operator()() const;
437     };
438
439 }
440
441 ///////////////////////////////hh.e////////////////////////////////////////
442 #include "Scheduler.cci"
443 //#include "Scheduler.ct"
444 #include "Scheduler.cti"
445 #endif
446
447 \f
448 // Local Variables:
449 // mode: c++
450 // fill-column: 100
451 // c-file-style: "senf"
452 // indent-tabs-mode: nil
453 // ispell-local-dictionary: "american"
454 // compile-command: "scons -u test"
455 // comment-column: 40
456 // End: