Documentation updates
[senf.git] / Scheduler / Scheduler.hh
index e5c045c..3329426 100644 (file)
@@ -1,9 +1,9 @@
 // $Id$
 //
 // Copyright (C) 2006
-// Fraunhofer Institut fuer offene Kommunikationssysteme (FOKUS)
-// Kompetenzzentrum fuer Satelitenkommunikation (SatCom)
-//     Stefan Bund <stefan.bund@fokus.fraunhofer.de>
+// Fraunhofer Institute for Open Communication Systems (FOKUS)
+// Competence Center NETwork research (NET), St. Augustin, GERMANY
+//     Stefan Bund <g0dil@berlios.de>
 //
 // This program is free software; you can redistribute it and/or modify
 // it under the terms of the GNU General Public License as published by
 #define HH_Scheduler_ 1
 
 // Custom includes
-#include <map>
-#include <queue>
-#include <boost/function.hpp>
-#include <boost/utility.hpp>
-#include <boost/call_traits.hpp>
-#include <boost/integer.hpp>
-#include "ClockService.hh"
+#include "../Utils/Logger/SenfLog.hh"
+#include "FdEvent.hh"
+#include "TimerEvent.hh"
+#include "SignalEvent.hh"
 
 //#include "scheduler.mpp"
 ///////////////////////////////hh.p////////////////////////////////////////
 
-/** \brief SENF Project namespace */
 namespace senf {
 
-    /** \brief Singleton class to manage the event loop
+/** \brief The Scheduler interface
 
-        This class manages a single select() type event loop. A customer of this class may register
-        any number of file descriptors with this class and pass callback functions to be called on
-        input, output or error. This functions are specified using boost::function objects (See <a
-        href="http://www.boost.org/doc/html/function.html">Boost.Function</a>)
+    The %scheduler API is comprised of two parts:
 
-        The Scheduler is based on a generic handle representation. The only information needed from
-        a handle, is the intrinsic file descriptor. Any object for which the statement
-        \code
-          int fd = retrieve_filehandle(object);
-        \endcode
-        is valid and places the relevant file descriptor into fd can be used as a Handle type. There
-        is an implementation of retrieve_filehandle(int) within the library to handle explicit file
-        descriptors. The <a href="../../../Socket/doc/html/index.html">Socket library</a> provides an
-        implementation of <tt>retrieve_filehandle(FileHandle handle)</tt>. If you want to support
-        some other handle type, just define an appropriate \c retrieve_filehandle function <em>in
-        that types namespace</em>.
-
-        It is important to note, that for every combination of file descriptor and event, only a \e
-        single handler may be installed. Installing more handlers does not make sense. If you need
-        to distribute data to several interested parties, you must take care of this yourself.
-
-        \todo Fix EventId parameter (probably to int) to allow |-ing without casting ...
-      */
-    class Scheduler
-        : boost::noncopyable
-    {
-    public:
-        ///////////////////////////////////////////////////////////////////////////
-        // Types
-
-        /** \brief Types of file descriptor events */
-        enum EventId { EV_NONE=0,
-                       EV_READ=1, EV_PRIO=2, EV_WRITE=4, 
-                       EV_ALL=7,
-                       EV_HUP=8, EV_ERR=16 };
-
-        /** \brief Template typedef for Callback type
-
-            This is a template typedef (which does not exist in C++) that is, a template class whose
-            sole member is a typedef symbol defining the callback type given the handle type.
-
-            The Callback is any callable object taking a \c Handle and an \c EventId as argument.
-         */
-        template <class Handle>
-        struct GenericCallback {
-            typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
-                                          EventId) > Callback;
-        };
-
-        /** \brief Callback type for timer events */
-        typedef boost::function<void ()> TimerCallback;
-
-        ///////////////////////////////////////////////////////////////////////////
-        ///\name Structors and default members
-        ///@{
-
-        // private default constructor
-        // no copy constructor
-        // no copy assignment
-        // default destructor
-        // no conversion constructors
-
-        /** \brief Return Scheduler instance
-
-            This static member is used to access the singleton instance. This member is save to
-            return a correctly initialized Scheduler instance even if called at global construction
-            time
-
-            \implementation This static member just defines the Scheduler as a static method
-                variable. The C++ standard then provides above guarantee. The instance will be
-                initialized the first time, the code flow passes the variable declaration found in
-                the instance() body.
-
-            \fixme TimerQueue as \c map \e and \c priority_queue doesn't make sense ...
-         */
-        static Scheduler & instance();
-
-        ///@}
-        ///////////////////////////////////////////////////////////////////////////
-
-        template <class Handle>
-        void add(Handle const & handle,
-                 typename GenericCallback<Handle>::Callback const & cb,
-                 int eventMask = EV_ALL); ///< Add file handle event callback
-                                        /**< add() will add a callback to the Scheduler. The
-                                             callback will be called for the given type of event on
-                                             the given  arbitrary file-descriptor or
-                                             handle-like object. If there already is a Callback
-                                             registered for one of the events requested, the new
-                                             handler will replace the old one.
-                                             \param[in] handle file descriptor or handle providing
-                                                 the Handle interface defined above.
-                                             \param[in] cb callback
-                                             \param[in] eventMask arbitrary combination via '|'
-                                                 operator of EventId designators. */
-        template <class Handle>
-        void remove(Handle const & handle, int eventMask = EV_ALL); ///< Remove event callback
-                                        /**< remove() will remove any callback registered for any of
-                                             the given events on the given file descriptor or handle
-                                             like object.
-                                             \param[in] handle file descriptor or handle providing
-                                                 the Handle interface defined above.
-                                             \param[in] eventMask arbitrary combination via '|'
-                                                 operator of EventId designators. */
-
-        unsigned timeout(ClockService::clock_type timeout, TimerCallback const & cb); 
-                                        ///< Add timeout event
-                                        /**< \param[in] timeout timeout in nanoseconds
-                                             \param[in] cb callback to call after \a timeout
-                                                 milliseconds
-                                             \todo Return some kind of handle/pointer and add
-                                                 support to update or revoke a timeout */
-
-        void cancelTimeout(unsigned id);
-
-        void process();                 ///< Event handler main loop
-                                        /**< This member must be called at some time to enter the
-                                             event handler main loop. Only while this function is
-                                             running any events are handled. The call will return
-                                             only, if any callback calls terminate(). */
-        void terminate();               ///< Called by callbacks to terminate the main loop
-                                        /**< This member may be called by any callback to tell the
-                                             main loop to terminate. The main loop will return to
-                                             it's caller after the currently running callback
-                                             returns. */
-        
-        ClockService::clock_type eventTime() const; ///< Return date/time of last event
-
-    protected:
+    \li Specific event classes, one for each type of event.
+    \li Some generic functions implemented in the \ref senf::scheduler namespace.
 
-    private:
-        typedef boost::function<void (EventId)> SimpleCallback;
+    Events are registered via the respective event class. The (global) functions are used to enter
+    the application main-loop or query for global information.
 
-        Scheduler();
+    \autotoc
 
-        void do_add(int fd, SimpleCallback const & cb, int eventMask = EV_ALL);
-        void do_remove(int fd, int eventMask = EV_ALL);
 
-        /** \brief Descriptor event specification
-            \internal */
-        struct EventSpec
-        {
-            SimpleCallback cb_read;
-            SimpleCallback cb_prio;
-            SimpleCallback cb_write;
+    \section sched_objects Event classes
 
-            int epollMask() const;
-        };
+    Every event registration is represented by a class instance of an event specific class:
 
-        /** \brief Timer event specification
-            \internal */
-        struct TimerSpec
-        {
-            TimerSpec() : timeout(), cb() {}
-            TimerSpec(ClockService::clock_type timeout_, TimerCallback cb_, unsigned id_)
-                : timeout(timeout_), cb(cb_), id(id_), canceled(false) {}
+    \li senf::scheduler::FdEvent for file descriptor events
+    \li senf::scheduler::TimerEvent for single-shot deadline timer events
+    \li senf::scheduler::SignalEvent for UNIX signal events
 
-            bool operator< (TimerSpec const & other) const
-                { return timeout > other.timeout; }
+    These instance are owned and managed by the user of the scheduler \e not by the scheduler so the
+    RAII concept can be used.
 
-            ClockService::clock_type timeout;
-            TimerCallback cb;
-            unsigned id;
-            bool canceled;
-        };
+    \code
+    class SomeServer
+    {
+        SomeSocketHandle handle_;
+        senf::scheduler::FdEvent event_;
 
-        typedef std::map<int,EventSpec> FdTable;
-        typedef std::map<unsigned,TimerSpec> TimerMap;
+    public:
+        SomeServer(SomeSocketHandle handle)
+            : handle_ (handle), 
+              event_ ("SomeServer handler", senf::membind(&SomeServer::readData, this),
+                      handle, senf::scheduler::FdEvent::EV_READ)
+        {}
 
-        struct TimerSpecCompare
+        void readData(int events)
         {
-            typedef TimerMap::iterator first_argument_type;
-            typedef TimerMap::iterator second_argument_type;
-            typedef bool result_type;
-            
-            result_type operator()(first_argument_type a, second_argument_type b);
-        };
-
-        typedef std::priority_queue<TimerMap::iterator, std::vector<TimerMap::iterator>, 
-                                    TimerSpecCompare> TimerQueue;
-
-        FdTable fdTable_;
-        unsigned timerIdCounter_;
-        TimerQueue timerQueue_;
-        TimerMap timerMap_;
-        int epollFd_;
-        bool terminate_;
-        ClockService::clock_type eventTime_;
+            // read data from handle_, check for eof and so on.
+        }
     };
+    \endcode
+
+    The event is defined as a class member variable. When the event member is initialized in the
+    constructor, the event is automatically registered (except if the optional \a initiallyEnabled
+    flag argument is set to \c false). The Destructor will automatically remove the event from the
+    scheduler and ensure, that no dead code is called accidentally.
+
+    The process is the same for the other event types or when registering multiple events. For
+    detailed information on the constructor arguments and other features see the event class
+    documentation referenced below.
+
+
+    \section sched_handlers Specifying handlers
+
+    All handlers are specified as generic <a
+    href="http://www.boost.org/doc/html/function.html">Boost.Function</a> objects. This allows to
+    pass any callable as a handler. Depending on the type of handler, some additional arguments may
+    be passed to the handler by the %scheduler.
+
+    If you need to pass additional information to your handler, use <a
+    href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a>:
+    \code
+    // Handle callback function
+    void callback(UDPv4ClientSocketHandle handle, senf::Scheduler::EventId event) {..}
+    // Pass 'handle' as additional first argument to callback()
+    senf::scheduler::FdEvent event ("name", boost::bind(&callback, handle, _1), 
+                                    handle, senf::scheduler::FdEvent::EV_READ);
+     // Timeout function
+    void timeout( int n) {..}
+    // Call timeout() handler with argument 'n'
+    senf::scheduler::TimerEvent timer ("name", boost::bind(&timeout, n),
+                                       senf::ClockService::now() + senf::ClockService::seconds(1));
+    \endcode
+
+    To use member-functions as callbacks, use either <a
+    href="http://www.boost.org/libs/bind/bind.html">Boost.Bind</a> or senf::membind()
+    \code
+    // e.g. in Foo::Foo() constructor:
+    Foo::Foo()
+        : handle_ (...),
+          readevent_ ("Foo read", senf::membind(&Foo::callback, this), 
+                      handle_, senf::scheduler::FdEvent::EV_READ)
+    { ... }
+    \endcode
+
+    The handler is identified by an arbitrary, user specified name. This name is used in error
+    messages to identify the failing handler.
+
+    \todo Fix the file support to use threads (?) fork (?) and a pipe so it works reliably even
+        over e.g. NFS.
+  */
+namespace scheduler {
+
+    /** \brief Event handler main loop 
+        
+        This member must be called at some time to enter the event handler main loop. Only while
+        this function is running any events are handled. The call will return if
+        \li a callback calls terminate()
+        \li the run queue becomes empty. 
+     */    
+    void process();                     
+
+    /** \brief Called by callbacks to terminate the main loop
+
+        This member may be called by any callback to tell the main loop to terminate. The main loop
+        will return to it's caller after the currently running callback returns. 
+     */
+    void terminate(); 
 
-    /** \brief Default file descriptor accessor
+    /** \brief Return date/time of last event
 
-        retrieve_filehandle() provides the Scheduler with support for explicit file descriptors as
-        file handle argument.
+        This is the timestamp, the last event has been signaled. This is the real time at which the
+        event is delivered \e not the time it should have been delivered (in the case of timers). 
+     */
+    ClockService::clock_type eventTime(); 
+
+    /** \brief Set task watchdog timeout */
+    void taskTimeout(unsigned ms); 
+
+    /** \brief Current task watchdog timeout */
+    unsigned taskTimeout(); 
+
+    /** \brief Number of watchdog events */
+    unsigned hangCount(); 
+
+    /** \brief Restart scheduler
+        
+        This call will restart all scheduler dispatchers (timers, signals, file descriptors). This
+        is necessary after a fork().
+        \warning This call will \e remove all registered events from the scheduler
+     */
+    void restart(); 
 
-        \relates Scheduler
+    /** \brief %scheduler specific time source for Utils/Logger framework
+
+        This time source may be used to provide timing information for log messages within the
+        Utils/Logger framework. This time source will use Scheduler::eventTime() to provide timing
+        information.
+
+        \code
+        senf::log::timeSource<senf::scheduler::LogTimeSource>();
+        \endcode
+
+        Using this information reduces the number of necessary ClockService::now() calls and thus
+        the number of system calls.
      */
-    int retrieve_filehandle(int fd);
+    struct LogTimeSource : public senf::log::TimeSource
+    {
+        senf::log::time_type operator()() const;
+    };
 
-}
+}}
 
 ///////////////////////////////hh.e////////////////////////////////////////
 #include "Scheduler.cci"
 //#include "Scheduler.ct"
-#include "Scheduler.cti"
+//#include "Scheduler.cti"
 #endif
 
 \f