89e9d2386f974cf107509face7fec3dac7ea6c82
[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 "../Utils/Logger/SenfLog.hh"
32 #include "FdDispatcher.hh"
33 #include "TimerDispatcher.hh"
34 #include "SignalDispatcher.hh"
35 #include "FileDispatcher.hh"
36 #include "../Utils/Logger/SenfLog.hh"
37
38 //#include "scheduler.mpp"
39 ///////////////////////////////hh.p////////////////////////////////////////
40
41 /** \brief SENF Project namespace */
42 namespace senf {
43
44     /** \brief Visible scheduler interface
45
46         The %scheduler singleton manages access to the %scheduler library. It provides access to
47         several event dispatchers:
48         \li File descriptor notifications
49         \li Timeouts
50         \li UNIX Signals
51
52         The %scheduler is entered by calling it's process() member. This call will continue to run as
53         long as there is something to do, or until one of the handlers calls terminate(). The
54         %scheduler has 'something to do' as long as there is any file descriptor or timeout active.
55
56         The %scheduler only provides low level primitive scheduling capability. Additional helpers
57         are defined on top of this functionality (e.g. ReadHelper or WriteHelper or the interval
58         timers of the PPI).
59
60
61         \section sched_handlers Specifying handlers
62
63         All handlers are passed as generic <a
64         href="http://www.boost.org/doc/html/function.html">Boost.Function</a> objects. This allows
65         to pass any callable as a handler. Depending on the type of handler, some additional
66         arguments may be passed to the handler by the %scheduler. 
67
68         If you need to pass additional information to your handler, use <a
69         href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a>:
70         \code
71         // Handle callback function
72         void callback(UDPv4ClientSocketHandle handle, senf::Scheduler::EventId event) {..}
73         // Pass 'handle' as additional first argument to callback()
74         Scheduler::instance().add(handle, boost::bind(&callback, handle, _1), EV_READ)
75          // Timeout function
76         void timeout( int n) {..}
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)), EV_READ)
86         \endcode
87
88         The handler can also be identified by an arbitrary, user specified name. This name is used
89         in error messages to identify the failing handler.
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 which again is based on POSIX timers. Registering a timeout will fire
129         the callback when the target time is reached. The timer may be canceled by passing the
130         returned \a id to cancelTimeout().
131
132
133         \section sched_signals Registering POSIX/UNIX signals
134
135         The %scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
136         %scheduler will be handled \e synchronously within the event loop.
137         \code
138         Scheduler::instance().registerSignal(SIGUSR1, &callback);
139         Scheduler::instance().unregisterSignal(SIGUSR1);
140         \endcode
141         When registering a signal with the %scheduler, that signal will automatically be blocked so
142         it can be handled within the %scheduler. 
143
144         A registered signal does \e not count as 'something to do'. It is therefore not possible to
145         wait for signals \e only.
146
147         \todo Change the Scheduler API to use RAII. Additionally, this will remove all dynamic
148             memory allocations from the scheduler.
149         \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
150             over e.g. NFS.
151       */
152     class Scheduler
153         : boost::noncopyable
154     {
155     public:
156
157         SENF_LOG_CLASS_AREA();
158
159         ///////////////////////////////////////////////////////////////////////////
160         // Types
161
162         /** \brief Types of file descriptor events 
163
164             These events are grouped into to classes:
165             \li Ordinary file descriptor events for which handlers may be registered. These are
166                 EV_READ, EV_PRIO and EV_WRITE. EV_ALL is a combination of these three.
167             \li Error flags. These additional flags may be passed to a handler to pass an error
168                 condition to the handler. 
169          */
170         enum EventId {
171             EV_NONE  = 0                              /**< No event */
172           , EV_READ  = scheduler::FdManager::EV_READ  /**< File descriptor is readable */
173           , EV_PRIO  = scheduler::FdManager::EV_PRIO  /**< File descriptor has OOB data */
174           , EV_WRITE = scheduler::FdManager::EV_WRITE /**< File descriptor is writable */
175           , EV_ALL   = scheduler::FdManager::EV_READ
176                      | scheduler::FdManager::EV_PRIO
177                      | scheduler::FdManager::EV_WRITE /**< Used to register all events at once
178                                                            (read/prio/write) */
179           , EV_HUP   = scheduler::FdManager::EV_HUP   /**< Hangup condition on file handle */
180           , EV_ERR   = scheduler::FdManager::EV_ERR   /**< Error condition on file handle */
181         };
182
183         /** \brief Callback type for file descriptor events */
184         typedef boost::function<void (int)> FdCallback;
185
186         /** \brief Callback type for timer events */
187         typedef boost::function<void ()> SimpleCallback;
188
189         /** \brief Callback type for signal events */
190         typedef boost::function<void (siginfo_t const &)> SignalCallback;
191
192         /** \brief Timer id type */
193         typedef scheduler::TimerDispatcher::timer_id timer_id;
194
195         ///////////////////////////////////////////////////////////////////////////
196         ///\name Structors and default members
197         ///@{
198
199         // private default constructor
200         // no copy constructor
201         // no copy assignment
202         // default destructor
203         // no conversion constructors
204
205         /** \brief Return %scheduler instance
206
207             This static member is used to access the singleton instance. This member is save to
208             return a correctly initialized %scheduler instance even if called at global construction
209             time
210          */
211         static Scheduler & instance();
212
213         ///@}
214         ///////////////////////////////////////////////////////////////////////////
215
216         ///\name File Descriptors
217         ///\{
218
219         template <class Handle>
220         void add(std::string const & name, Handle const & handle, FdCallback const & cb,
221                  int eventMask = EV_ALL);  ///< Add file handle event callback
222                                         /**< add() will add a callback to the %scheduler. The
223                                              callback will be called for the given type of event on
224                                              the given  arbitrary file-descriptor or
225                                              handle-like object. If there already is a Callback
226                                              registered for one of the events requested, the new
227                                              handler will replace the old one.
228                                              \param[in] name descriptive name to identify the
229                                                  callback.
230                                              \param[in] handle file descriptor or handle providing
231                                                  the Handle interface defined above.
232                                              \param[in] cb callback
233                                              \param[in] eventMask arbitrary combination via '|'
234                                                  operator of \ref senf::Scheduler::EventId "EventId"
235                                                  designators. */
236  
237         template <class Handle>        
238         void add(Handle const & handle, FdCallback const & cb,
239                  int eventMask = EV_ALL); ///< Add file handle event callback
240                                         /**< \see add() */
241
242
243         template <class Handle>
244         void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
245                                         /**< remove() will remove any callback registered for any of
246                                              the given events on the given file descriptor or handle
247                                              like object.
248                                              \param[in] handle file descriptor or handle providing
249                                                  the Handle interface defined above.
250                                              \param[in] eventMask arbitrary combination via '|'
251                                                  operator of \ref senf::Scheduler::EventId "EventId"
252                                                  designators. */
253
254         ///\}
255
256         ///\name Timeouts
257         ///\{
258
259         timer_id timeout(std::string const & name, ClockService::clock_type timeout, 
260                          SimpleCallback const & cb); 
261                                         ///< Add timeout event
262                                         /**< \returns timer id
263                                              \param[in] name descriptive name to identify the
264                                                  callback.
265                                              \param[in] timeout timeout in nanoseconds
266                                              \param[in] cb callback to call after \a timeout
267                                                  milliseconds */
268
269         timer_id timeout(ClockService::clock_type timeout, SimpleCallback const & cb); 
270                                         ///< Add timeout event
271                                         /**< \see timeout() */
272
273         void cancelTimeout(timer_id id); ///< Cancel timeout \a id
274
275 #ifndef DOXYGEN
276         ClockService::clock_type timeoutEarly() const;
277         void timeoutEarly(ClockService::clock_type v);
278
279         ClockService::clock_type timeoutAdjust() const;
280         void timeoutAdjust(ClockService::clock_type v);
281 #endif
282
283         ///\}
284
285         ///\name Signal handlers
286         ///\{
287         
288         void registerSignal(unsigned signal, SignalCallback 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         ///\}
298
299         void process();                 ///< Event handler main loop
300                                         /**< This member must be called at some time to enter the
301                                              event handler main loop. Only while this function is
302                                              running any events are handled. The call will return
303                                              only, if any callback calls terminate(). */
304
305         void terminate();               ///< Called by callbacks to terminate the main loop
306                                         /**< This member may be called by any callback to tell the
307                                              main loop to terminate. The main loop will return to
308                                              it's caller after the currently running callback
309                                              returns. */
310         
311         ClockService::clock_type eventTime() const; ///< Return date/time of last event
312                                         /**< This is the timestamp, the last event has been
313                                              signaled. This is the real time at which the event is
314                                              delivered \e not the time it should have been delivered
315                                              (in the case of timers). */
316
317         unsigned hangCount() const;
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_add(std::string const & name, int fd, FdCallback const & cb, 
326                     int eventMask = EV_ALL);
327         void do_remove(int fd, int eventMask);
328
329         bool terminate_;
330         scheduler::FdManager manager_;
331         scheduler::FIFORunner runner_;
332
333         scheduler::FdDispatcher fdDispatcher_;
334         scheduler::TimerDispatcher timerDispatcher_;
335         scheduler::SignalDispatcher signalDispatcher_;
336         scheduler::FileDispatcher fileDispatcher_;
337     };
338
339     /** \brief Default file descriptor accessor
340
341         retrieve_filehandle() provides the %scheduler with support for explicit file descriptors as
342         file handle argument.
343
344         \relates Scheduler
345      */
346     int retrieve_filehandle(int fd);
347
348     /** \brief %scheduler specific time source for Utils/Logger framework
349
350         This time source may be used to provide timing information for log messages within the
351         Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
352         information.
353      */
354     struct SchedulerLogTimeSource : public senf::log::TimeSource
355     {
356         senf::log::time_type operator()() const;
357     };
358
359 }
360
361 ///////////////////////////////hh.e////////////////////////////////////////
362 #include "Scheduler.cci"
363 //#include "Scheduler.ct"
364 #include "Scheduler.cti"
365 #endif
366
367 \f
368 // Local Variables:
369 // mode: c++
370 // fill-column: 100
371 // c-file-style: "senf"
372 // indent-tabs-mode: nil
373 // ispell-local-dictionary: "american"
374 // compile-command: "scons -u test"
375 // comment-column: 40
376 // End: