Packets/DefaultBundle: Document finalize() action
[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
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     class Scheduler
158         : boost::noncopyable
159     {
160     public:
161         ///////////////////////////////////////////////////////////////////////////
162         // Types
163
164         /** \brief Types of file descriptor events */
165         enum EventId { EV_NONE=0,
166                        EV_READ=1, EV_PRIO=2, EV_WRITE=4, 
167                        EV_ALL=7,
168                        EV_HUP=8, EV_ERR=16 };
169
170         /** \brief Template typedef for Callback type
171
172             This is a template typedef (which does not exist in C++) that is, a template class whose
173             sole member is a typedef symbol defining the callback type given the handle type.
174
175             The Callback is any callable object taking a \c Handle and an \c EventId as argument.
176         template <class Handle>
177         struct GenericCallback {
178             typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
179                                           EventId) > Callback;
180         };
181          */
182
183         typedef boost::function<void (EventId)> FdCallback;
184
185         /** \brief Callback type for timer events */
186         typedef boost::function<void ()> SimpleCallback;
187
188         ///////////////////////////////////////////////////////////////////////////
189         ///\name Structors and default members
190         ///@{
191
192         // private default constructor
193         // no copy constructor
194         // no copy assignment
195         // default destructor
196         // no conversion constructors
197
198         /** \brief Return Scheduler instance
199
200             This static member is used to access the singleton instance. This member is save to
201             return a correctly initialized Scheduler instance even if called at global construction
202             time
203
204             \implementation This static member just defines the Scheduler as a static method
205                 variable. The C++ standard then provides above guarantee. The instance will be
206                 initialized the first time, the code flow passes the variable declaration found in
207                 the instance() body.
208          */
209         static Scheduler & instance();
210
211         ///@}
212         ///////////////////////////////////////////////////////////////////////////
213
214         ///\name File Descriptors
215         ///\{
216
217         template <class Handle>
218         void add(Handle const & handle, FdCallback const & cb,
219                  int eventMask = EV_ALL); ///< Add file handle event callback
220                                         /**< add() will add a callback to the Scheduler. The
221                                              callback will be called for the given type of event on
222                                              the given  arbitrary file-descriptor or
223                                              handle-like object. If there already is a Callback
224                                              registered for one of the events requested, the new
225                                              handler will replace the old one.
226                                              \param[in] handle file descriptor or handle providing
227                                                  the Handle interface defined above.
228                                              \param[in] cb callback
229                                              \param[in] eventMask arbitrary combination via '|'
230                                                  operator of EventId designators. */
231         template <class Handle>
232         void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
233                                         /**< remove() will remove any callback registered for any of
234                                              the given events on the given file descriptor or handle
235                                              like object.
236                                              \param[in] handle file descriptor or handle providing
237                                                  the Handle interface defined above.
238                                              \param[in] eventMask arbitrary combination via '|'
239                                                  operator of EventId designators. */
240
241         ///\}
242
243         ///\name Timeouts
244         ///\{
245
246         unsigned timeout(ClockService::clock_type timeout, SimpleCallback const & cb); 
247                                         ///< Add timeout event
248                                         /**< \param[in] timeout timeout in nanoseconds
249                                              \param[in] cb callback to call after \a timeout
250                                                  milliseconds */
251
252         void cancelTimeout(unsigned id); ///< Cancel timeout \a id
253
254         ClockService::clock_type timeoutEarly() const;
255                                         ///< Fetch the \a timeoutEarly parameter
256         void timeoutEarly(ClockService::clock_type v);
257                                         ///< Set the \a timeoutEarly parameter
258
259         ClockService::clock_type timeoutAdjust() const;\
260                                         ///< Fetch the \a timeoutAdjust parameter
261         void timeoutAdjust(ClockService::clock_type v);
262                                         ///< Set the \a timeoutAdjust parameter
263
264         ///\}
265
266         ///\name Signal handlers
267         ///\{
268         
269         void registerSignal(unsigned signal, SimpleCallback const & cb);
270                                         ///< Add signal handler
271                                         /**< \param[in] signal signal number to register handler for
272                                              \param[in] cb callback to call whenever \a signal is
273                                                  delivered. */
274
275         void unregisterSignal(unsigned signal);
276                                         ///< Remove signal handler for \a signal
277
278         struct InvalidSignalNumberException : public std::exception
279         { virtual char const * what() const throw() 
280                 { return "senf::Scheduler::InvalidSignalNumberException"; } };
281
282
283         ///\}
284
285         void process();                 ///< Event handler main loop
286                                         /**< This member must be called at some time to enter the
287                                              event handler main loop. Only while this function is
288                                              running any events are handled. The call will return
289                                              only, if any callback calls terminate(). */
290
291         void terminate();               ///< Called by callbacks to terminate the main loop
292                                         /**< This member may be called by any callback to tell the
293                                              main loop to terminate. The main loop will return to
294                                              it's caller after the currently running callback
295                                              returns. */
296         
297         ClockService::clock_type eventTime() const; ///< Return date/time of last event
298
299     protected:
300
301     private:
302         Scheduler();
303
304         void do_add(int fd, FdCallback const & cb, int eventMask = EV_ALL);
305         void do_remove(int fd, int eventMask = EV_ALL);
306
307         void registerSigHandlers();
308         static void sigHandler(int signal, ::siginfo_t * siginfo, void *);
309
310 #       ifndef DOXYGEN
311
312         /** \brief Descriptor event specification
313             \internal */
314         struct EventSpec
315         {
316             FdCallback cb_read;
317             FdCallback cb_prio;
318             FdCallback cb_write;
319
320             int epollMask() const;
321         };
322
323         /** \brief Timer event specification
324             \internal */
325         struct TimerSpec
326         {
327             TimerSpec() : timeout(), cb() {}
328             TimerSpec(ClockService::clock_type timeout_, SimpleCallback cb_, unsigned id_)
329                 : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
330
331             bool operator< (TimerSpec const & other) const
332                 { return timeout > other.timeout; }
333
334             ClockService::clock_type timeout;
335             SimpleCallback cb;
336             unsigned id;
337             bool canceled;
338         };
339
340 #       endif 
341
342         typedef std::map<int,EventSpec> FdTable;
343         typedef std::map<unsigned,TimerSpec> TimerMap; // sorted by id
344
345 #       ifndef DOXYGEN
346
347         struct TimerSpecCompare
348         {
349             typedef TimerMap::iterator first_argument_type;
350             typedef TimerMap::iterator second_argument_type;
351             typedef bool result_type;
352             
353             result_type operator()(first_argument_type a, second_argument_type b);
354         };
355
356 #       endif
357
358         typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>, 
359                                     TimerSpecCompare> TimerQueue; // sorted by time
360
361         typedef std::vector<SimpleCallback> SigHandlers;
362
363         FdTable fdTable_;
364
365         unsigned timerIdCounter_;
366         TimerQueue timerQueue_;
367         TimerMap timerMap_;
368
369         SigHandlers sigHandlers_;
370         ::sigset_t sigset_;
371         int sigpipe_[2];
372
373         int epollFd_;
374         bool terminate_;
375         ClockService::clock_type eventTime_;
376         ClockService::clock_type eventEarly_;
377         ClockService::clock_type eventAdjust_;
378     };
379
380     /** \brief Default file descriptor accessor
381
382         retrieve_filehandle() provides the Scheduler with support for explicit file descriptors as
383         file handle argument.
384
385         \relates Scheduler
386      */
387     int retrieve_filehandle(int fd);
388
389     /** \brief Scheduler specific time source for Utils/Logger framework
390
391         This time source may be used to provide timing information for log messages within the
392         Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
393         information.
394      */
395     struct SchedulerLogTimeSource : public senf::log::TimeSource
396     {
397         boost::posix_time::ptime operator()() const;
398     };
399
400 }
401
402 ///////////////////////////////hh.e////////////////////////////////////////
403 #include "Scheduler.cci"
404 //#include "Scheduler.ct"
405 #include "Scheduler.cti"
406 #endif
407
408 \f
409 // Local Variables:
410 // mode: c++
411 // fill-column: 100
412 // c-file-style: "senf"
413 // indent-tabs-mode: nil
414 // ispell-local-dictionary: "american"
415 // compile-command: "scons -u test"
416 // comment-column: 40
417 // End: