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