Console: Implement BSDSocketAddress and BSDAddressingPolicy
[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 <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/SenfLog.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
65         \section sched_handlers Specifying handlers
66
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. 
71
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>:
74         \code
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)
79          // Timeout function
80         void timeout( int n) {..}
81         // Call timeout() handler with argument 'n'
82         Scheduler::instance().timeout(boost::bind(&timeout, n))
83         \endcode
84
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()
87         \code
88         // e.g. in Foo::Foo() constructor:
89         Scheduler::instance().add(handle_, senf::membind(&Foo::callback, this)), EV_READ)
90         \endcode
91         
92
93         \section sched_fd Registering file descriptors
94         
95         File descriptors are managed using add() or remove()
96         \code
97         Scheduler::instance().add(handle, &callback, EV_ALL);
98         Scheduler::instance().remove(handle);
99         \endcode 
100
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.
104
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).
107
108         The %scheduler will accept any object as \a handle argument as long as retrieve_filehandle()
109         may be called on that object
110         \code
111         int fd = retrieve_filehandle(handle);
112         \endcode 
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)
116
117
118         \section sched_timers Registering timers
119
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()
123         \code
124         int id = Scheduler::instance().timeout(Scheduler::instance().eventTime() + ClockService::milliseconds(100),
125                                                &callback);
126         Scheduler::instance().cancelTimeout(id);
127         \endcode 
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().
131
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
138         granularity). 
139
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.
143
144
145         \section sched_signals Registering POSIX/UNIX signals
146
147         The %scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
148         %scheduler will be handled \e synchronously within the event loop.
149         \code
150         Scheduler::instance().registerSignal(SIGUSR1, &callback);
151         Scheduler::instance().unregisterSignal(SIGUSR1);
152         \endcode
153         When registering a signal with the %scheduler, that signal will automatically be blocked so
154         it can be handled within the %scheduler. 
155
156         A registered signal does \e not count as 'something to do'. It is therefore not possible to
157         wait for signals \e only.
158
159         \todo Fix EventId parameter (probably to int) to allow |-ing without casting ...
160         
161         \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
162             over e.g. NFS.
163
164         \todo Add a check in the alarm callback which is already called every x seconds to check,
165             that a single callback is not blocking.
166       */
167     class Scheduler
168         : boost::noncopyable
169     {
170     public:
171
172         SENF_LOG_CLASS_AREA();
173
174         ///////////////////////////////////////////////////////////////////////////
175         // Types
176
177         /** \brief Types of file descriptor events 
178
179             These events are grouped into to classes:
180             \li Ordinary file descriptor events for which handlers may be registered. These are
181                 EV_READ, EV_PRIO and EV_WRITE. EV_ALL is a combination of these three.
182             \li Error flags. These additional flags may be passed to a handler to pass an error
183                 condition to the handler. 
184          */
185         enum EventId { 
186             EV_NONE  =  0   /**< No event */
187           , EV_READ  =  1   /**< File descriptor is readable */
188           , EV_PRIO  =  2   /**< File descriptor has OOB data */
189           , EV_WRITE =  4   /**< File descriptor is writable */
190           , EV_ALL   =  7   /**< Used to register all events at once (read/prio/write) */
191           , EV_HUP   =  8   /**< Hangup condition on file handle */
192           , EV_ERR   = 16   /**< Error condition on file handle */
193         };
194
195         /** \brief Template typedef for Callback type
196
197             This is a template typedef (which does not exist in C++) that is, a template class whose
198             sole member is a typedef symbol defining the callback type given the handle type.
199
200             The Callback is any callable object taking a \c Handle and an \c EventId as argument.
201             \code
202             template <class Handle>
203             struct GenericCallback {
204                 typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
205                                               EventId) > Callback;
206             };
207             \endcode
208          */
209         typedef boost::function<void (EventId)> FdCallback;
210
211         /** \brief Callback type for timer events */
212         typedef boost::function<void ()> SimpleCallback;
213
214         ///////////////////////////////////////////////////////////////////////////
215         ///\name Structors and default members
216         ///@{
217
218         // private default constructor
219         // no copy constructor
220         // no copy assignment
221         // default destructor
222         // no conversion constructors
223
224         /** \brief Return %scheduler instance
225
226             This static member is used to access the singleton instance. This member is save to
227             return a correctly initialized %scheduler instance even if called at global construction
228             time
229
230             \implementation This static member just defines the %scheduler as a static method
231                 variable. The C++ standard then provides above guarantee. The instance will be
232                 initialized the first time, the code flow passes the variable declaration found in
233                 the instance() body.
234          */
235         static Scheduler & instance();
236
237         ///@}
238         ///////////////////////////////////////////////////////////////////////////
239
240         ///\name File Descriptors
241         ///\{
242
243         template <class Handle>
244         void add(Handle const & handle, FdCallback const & cb,
245                  int eventMask = EV_ALL); ///< Add file handle event callback
246                                         /**< add() will add a callback to the %scheduler. The
247                                              callback will be called for the given type of event on
248                                              the given  arbitrary file-descriptor or
249                                              handle-like object. If there already is a Callback
250                                              registered for one of the events requested, the new
251                                              handler will replace the old one.
252                                              \param[in] handle file descriptor or handle providing
253                                                  the Handle interface defined above.
254                                              \param[in] cb callback
255                                              \param[in] eventMask arbitrary combination via '|'
256                                                  operator of \ref senf::Scheduler::EventId "EventId"
257                                                  designators. */
258         template <class Handle>
259         void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
260                                         /**< remove() will remove any callback registered for any of
261                                              the given events on the given file descriptor or handle
262                                              like object.
263                                              \param[in] handle file descriptor or handle providing
264                                                  the Handle interface defined above.
265                                              \param[in] eventMask arbitrary combination via '|'
266                                                  operator of \ref senf::Scheduler::EventId "EventId"
267                                                  designators. */
268         ///\}
269
270         ///\name Timeouts
271         ///\{
272
273         unsigned timeout(ClockService::clock_type timeout, SimpleCallback const & cb); 
274                                         ///< Add timeout event
275                                         /**< \returns timer id
276                                              \param[in] timeout timeout in nanoseconds
277                                              \param[in] cb callback to call after \a timeout
278                                                  milliseconds */
279
280         void cancelTimeout(unsigned id); ///< Cancel timeout \a id
281
282         ClockService::clock_type timeoutEarly() const;
283                                         ///< Fetch the \a timeoutEarly parameter
284         void timeoutEarly(ClockService::clock_type v);
285                                         ///< Set the \a timeoutEarly parameter
286
287         ClockService::clock_type timeoutAdjust() const;\
288                                         ///< Fetch the \a timeoutAdjust parameter
289         void timeoutAdjust(ClockService::clock_type v);
290                                         ///< Set the \a timeoutAdjust parameter
291
292         ///\}
293
294         ///\name Signal handlers
295         ///\{
296         
297         void registerSignal(unsigned signal, SimpleCallback const & cb);
298                                         ///< Add signal handler
299                                         /**< \param[in] signal signal number to register handler for
300                                              \param[in] cb callback to call whenever \a signal is
301                                                  delivered. */
302
303         void unregisterSignal(unsigned signal);
304                                         ///< Remove signal handler for \a signal
305
306         /// The signal number passed to registerSignal or unregisterSignal is invalid
307         struct InvalidSignalNumberException : public senf::Exception
308         { InvalidSignalNumberException() 
309               : senf::Exception("senf::Scheduler::InvalidSignalNumberException"){} };
310
311
312         ///\}
313
314         void process();                 ///< Event handler main loop
315                                         /**< This member must be called at some time to enter the
316                                              event handler main loop. Only while this function is
317                                              running any events are handled. The call will return
318                                              only, if any callback calls terminate(). */
319
320         void terminate();               ///< Called by callbacks to terminate the main loop
321                                         /**< This member may be called by any callback to tell the
322                                              main loop to terminate. The main loop will return to
323                                              it's caller after the currently running callback
324                                              returns. */
325         
326         ClockService::clock_type eventTime() const; ///< Return date/time of last event
327                                         /**< This is the timestamp, the last event has been
328                                              signaled. This is the real time at which the event is
329                                              delivered \e not the time it should have been delivered
330                                              (in the case of timers). */
331
332     protected:
333
334     private:
335         Scheduler();
336
337         void do_add(int fd, FdCallback const & cb, int eventMask = EV_ALL);
338         void do_remove(int fd, int eventMask = EV_ALL);
339
340         void registerSigHandlers();
341         static void sigHandler(int signal, ::siginfo_t * siginfo, void *);
342
343 #       ifndef DOXYGEN
344
345         /** \brief Descriptor event specification
346             \internal */
347         struct EventSpec
348         {
349             FdCallback cb_read;
350             FdCallback cb_prio;
351             FdCallback cb_write;
352
353             EventSpec() : file(false) {}
354
355             int epollMask() const;
356
357             bool file;
358         };
359
360         /** \brief Timer event specification
361             \internal */
362         struct TimerSpec
363         {
364             TimerSpec() : timeout(), cb() {}
365             TimerSpec(ClockService::clock_type timeout_, SimpleCallback cb_, unsigned id_)
366                 : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
367
368             bool operator< (TimerSpec const & other) const
369                 { return timeout > other.timeout; }
370
371             ClockService::clock_type timeout;
372             SimpleCallback cb;
373             unsigned id;
374             bool canceled;
375         };
376
377 #       endif 
378
379         typedef std::map<int,EventSpec> FdTable;
380         typedef std::map<unsigned,TimerSpec> TimerMap; // sorted by id
381         typedef std::vector<unsigned> FdEraseList;
382
383 #       ifndef DOXYGEN
384
385         struct TimerSpecCompare
386         {
387             typedef TimerMap::iterator first_argument_type;
388             typedef TimerMap::iterator second_argument_type;
389             typedef bool result_type;
390             
391             result_type operator()(first_argument_type a, second_argument_type b);
392         };
393
394 #       endif
395
396         typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>, 
397                                     TimerSpecCompare> TimerQueue; // sorted by time
398
399         typedef std::vector<SimpleCallback> SigHandlers;
400
401         FdTable fdTable_;
402         FdEraseList fdErase_;
403         unsigned files_;
404
405         unsigned timerIdCounter_;
406         TimerQueue timerQueue_;
407         TimerMap timerMap_;
408
409         SigHandlers sigHandlers_;
410         ::sigset_t sigset_;
411         int sigpipe_[2];
412
413         int epollFd_;
414         bool terminate_;
415         ClockService::clock_type eventTime_;
416         ClockService::clock_type eventEarly_;
417         ClockService::clock_type eventAdjust_;
418     };
419
420     /** \brief Default file descriptor accessor
421
422         retrieve_filehandle() provides the %scheduler with support for explicit file descriptors as
423         file handle argument.
424
425         \relates Scheduler
426      */
427     int retrieve_filehandle(int fd);
428
429     /** \brief %scheduler specific time source for Utils/Logger framework
430
431         This time source may be used to provide timing information for log messages within the
432         Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
433         information.
434      */
435     struct SchedulerLogTimeSource : public senf::log::TimeSource
436     {
437         senf::log::time_type operator()() const;
438     };
439
440 }
441
442 ///////////////////////////////hh.e////////////////////////////////////////
443 #include "Scheduler.cci"
444 //#include "Scheduler.ct"
445 #include "Scheduler.cti"
446 #endif
447
448 \f
449 // Local Variables:
450 // mode: c++
451 // fill-column: 100
452 // c-file-style: "senf"
453 // indent-tabs-mode: nil
454 // ispell-local-dictionary: "american"
455 // compile-command: "scons -u test"
456 // comment-column: 40
457 // End: