7f6682195e698f35a2545f0217d085c59cb579d0
[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 "FdEvent.hh"
33 #include "TimerEvent.hh"
34 #include "SignalEvent.hh"
35 #include "../Utils/Logger/SenfLog.hh"
36
37 //#include "scheduler.mpp"
38 ///////////////////////////////hh.p////////////////////////////////////////
39
40 /** \brief SENF Project namespace */
41 namespace senf {
42
43     /** \brief Visible scheduler interface
44
45         The %scheduler singleton manages access to the %scheduler library. It provides access to
46         several event dispatchers:
47         \li File descriptor notifications
48         \li Timeouts
49         \li UNIX Signals
50
51         The %scheduler is entered by calling it's process() member. This call will continue to run as
52         long as there is something to do, or until one of the handlers calls terminate(). The
53         %scheduler has 'something to do' as long as there is any file descriptor or timeout active.
54
55         The %scheduler only provides low level primitive scheduling capability. Additional helpers
56         are defined on top of this functionality (e.g. ReadHelper or WriteHelper or the interval
57         timers of the PPI).
58
59
60         \section sched_handlers Specifying handlers
61
62         All handlers are passed as generic <a
63         href="http://www.boost.org/doc/html/function.html">Boost.Function</a> objects. This allows
64         to pass any callable as a handler. Depending on the type of handler, some additional
65         arguments may be passed to the handler by the %scheduler. 
66
67         If you need to pass additional information to your handler, use <a
68         href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a>:
69         \code
70         // Handle callback function
71         void callback(UDPv4ClientSocketHandle handle, senf::Scheduler::EventId event) {..}
72         // Pass 'handle' as additional first argument to callback()
73         Scheduler::instance().add(handle, boost::bind(&callback, handle, _1), EV_READ)
74          // Timeout function
75         void timeout( int n) {..}
76         // Call timeout() handler with argument 'n'
77         Scheduler::instance().timeout(boost::bind(&timeout, n))
78         \endcode
79
80         To use member-functions as callbacks, use either <a
81         href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a> or senf::membind()
82         \code
83         // e.g. in Foo::Foo() constructor:
84         Scheduler::instance().add(handle_, senf::membind(&Foo::callback, this)), EV_READ)
85         \endcode
86
87         The handler can also be identified by an arbitrary, user specified name. This name is used
88         in error messages to identify the failing handler.
89
90
91         \section sched_fd Registering file descriptors
92         
93         File descriptors are managed using add() or remove()
94         \code
95         Scheduler::instance().add(handle, &callback, EV_ALL);
96         Scheduler::instance().remove(handle);
97         \endcode 
98
99         The callback will be called with one additional argument. This argument is the event mask of
100         type EventId. This mask will tell, which of the registered events are signaled. The
101         additional flags EV_HUP or EV_ERR (on hangup or error condition) may be set additionally.
102
103         Only a single handler may be registered for any combination of file descriptor and event
104         (registering multiple callbacks for a single fd and event does not make sense).
105
106         The %scheduler will accept any object as \a handle argument as long as retrieve_filehandle()
107         may be called on that object
108         \code
109         int fd = retrieve_filehandle(handle);
110         \endcode 
111         to fetch the file handle given some abstract handle type. retrieve_filehandle() will be
112         found using ADL depending on the argument namespace. A default implementation is provided
113         for \c int arguments (file descriptors)
114
115
116         \section sched_timers Registering timers
117
118         The %scheduler has very simple timer support. There is only one type of timer: A single-shot
119         deadline timer. More complex timers are built based on this. Timers are managed using
120         timeout() and cancelTimeout()
121         \code
122         int id = Scheduler::instance().timeout(Scheduler::instance().eventTime() + ClockService::milliseconds(100),
123                                                &callback);
124         Scheduler::instance().cancelTimeout(id);
125         \endcode 
126         Timing is based on the ClockService, which provides a high resolution and strictly
127         monotonous time source which again is based on POSIX timers. Registering a timeout will fire
128         the callback when the target time is reached. The timer may be canceled by passing the
129         returned \a id to cancelTimeout().
130
131
132         \section sched_signals Registering POSIX/UNIX signals
133
134         The %scheduler also incorporates standard POSIX/UNIX signals. Signals registered with the
135         %scheduler will be handled \e synchronously within the event loop.
136         \code
137         Scheduler::instance().registerSignal(SIGUSR1, &callback);
138         Scheduler::instance().unregisterSignal(SIGUSR1);
139         \endcode
140         When registering a signal with the %scheduler, that signal will automatically be blocked so
141         it can be handled within the %scheduler. 
142
143         A registered signal does \e not count as 'something to do'. It is therefore not possible to
144         wait for signals \e only.
145
146         \todo Change the Scheduler API to use RAII. Additionally, this will remove all dynamic
147             memory allocations from the scheduler.
148         \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
149             over e.g. NFS.
150       */
151     class Scheduler
152         : boost::noncopyable
153     {
154     public:
155
156         SENF_LOG_CLASS_AREA();
157
158         ///////////////////////////////////////////////////////////////////////////
159         // Types
160
161         /** \brief Types of file descriptor events 
162
163             These events are grouped into to classes:
164             \li Ordinary file descriptor events for which handlers may be registered. These are
165                 EV_READ, EV_PRIO and EV_WRITE. EV_ALL is a combination of these three.
166             \li Error flags. These additional flags may be passed to a handler to pass an error
167                 condition to the handler. 
168          */
169         enum EventId {
170             EV_NONE  = 0                              /**< No event */
171           , EV_READ  = scheduler::FdManager::EV_READ  /**< File descriptor is readable */
172           , EV_PRIO  = scheduler::FdManager::EV_PRIO  /**< File descriptor has OOB data */
173           , EV_WRITE = scheduler::FdManager::EV_WRITE /**< File descriptor is writable */
174           , EV_ALL   = scheduler::FdManager::EV_READ
175                      | scheduler::FdManager::EV_PRIO
176                      | scheduler::FdManager::EV_WRITE /**< Used to register all events at once
177                                                            (read/prio/write) */
178           , EV_HUP   = scheduler::FdManager::EV_HUP   /**< Hangup condition on file handle */
179           , EV_ERR   = scheduler::FdManager::EV_ERR   /**< Error condition on file handle */
180         };
181
182         /** \brief Callback type for file descriptor events */
183         typedef boost::function<void (int)> FdCallback;
184
185         /** \brief Callback type for timer events */
186         typedef boost::function<void ()> SimpleCallback;
187
188         /** \brief Callback type for signal events */
189         typedef boost::function<void (siginfo_t const &)> SignalCallback;
190
191         ///////////////////////////////////////////////////////////////////////////
192         ///\name Structors and default members
193         ///@{
194
195         // private default constructor
196         // no copy constructor
197         // no copy assignment
198         // default destructor
199         // no conversion constructors
200
201         /** \brief Return %scheduler instance
202
203             This static member is used to access the singleton instance. This member is save to
204             return a correctly initialized %scheduler instance even if called at global construction
205             time
206          */
207         static Scheduler & instance();
208
209         ///@}
210         ///////////////////////////////////////////////////////////////////////////
211
212         void process();                 ///< Event handler main loop
213                                         /**< This member must be called at some time to enter the
214                                              event handler main loop. Only while this function is
215                                              running any events are handled. The call will return
216                                              only, if any callback calls terminate(). */
217
218         void terminate();               ///< Called by callbacks to terminate the main loop
219                                         /**< This member may be called by any callback to tell the
220                                              main loop to terminate. The main loop will return to
221                                              it's caller after the currently running callback
222                                              returns. */
223         
224         ClockService::clock_type eventTime() const; ///< Return date/time of last event
225                                         /**< This is the timestamp, the last event has been
226                                              signaled. This is the real time at which the event is
227                                              delivered \e not the time it should have been delivered
228                                              (in the case of timers). */
229
230         void taskTimeout(unsigned ms);
231         unsigned taskTimeout() const;
232         unsigned hangCount() const;
233
234         void restart();
235
236     protected:
237
238     private:
239         Scheduler();
240
241         bool terminate_;
242     };
243
244     /** \brief %scheduler specific time source for Utils/Logger framework
245
246         This time source may be used to provide timing information for log messages within the
247         Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
248         information.
249      */
250     struct SchedulerLogTimeSource : public senf::log::TimeSource
251     {
252         senf::log::time_type operator()() const;
253     };
254
255 }
256
257 ///////////////////////////////hh.e////////////////////////////////////////
258 #include "Scheduler.cci"
259 //#include "Scheduler.ct"
260 //#include "Scheduler.cti"
261 #endif
262
263 \f
264 // Local Variables:
265 // mode: c++
266 // fill-column: 100
267 // c-file-style: "senf"
268 // indent-tabs-mode: nil
269 // ispell-local-dictionary: "american"
270 // compile-command: "scons -u test"
271 // comment-column: 40
272 // End: