Packets: Fix VariantParser invalid parser access bug
[senf.git] / Scheduler / Scheduler.hh
index 785dce9..a8cfe59 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>
+// Copyright (C) 2006
+// 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
 // Free Software Foundation, Inc.,
 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
-// TODO: Fix EventId parameter (probably to int) to allow |-ing without casting ...
-
-
-/** \mainpage The SENF Scheduler library
-
+/** \file
+    \brief Scheduler public header
  */
 
-#ifndef HH_Scheduler_
-#define HH_Scheduler_ 1
+#ifndef HH_SENF_Scheduler_Scheduler_
+#define HH_SENF_Scheduler_Scheduler_ 1
 
 // Custom includes
-#include <map>
-#include <queue>
-#include <boost/function.hpp>
-#include <boost/utility.hpp>
-#include <boost/call_traits.hpp>
-
-#include "Utils/MicroTime.hh"
+#include "../Utils/Logger/SenfLog.hh"
+#include "FdEvent.hh"
+#include "TimerEvent.hh"
+#include "SignalEvent.hh"
+#include "EventHook.hh"
 
 //#include "scheduler.mpp"
 ///////////////////////////////hh.p////////////////////////////////////////
 
-namespace satcom {
-namespace lib {
+namespace senf {
+
+/** \brief The Scheduler interface
+
+    The %scheduler API is comprised of two parts:
+
+    \li Specific \ref sched_objects, one for each type of event.
+    \li Some <a href="#autotoc-7.">generic functions</a> implemented in the \ref senf::scheduler
+        namespace.
+
+    Events are registered via the respective event class. The (global) functions are used to enter
+    the application main-loop or query for global information.
+
+    \autotoc
+
+
+    \section sched_objects Event classes
+
+    The Scheduler is based on the RAII principle: Every event is represented by a class
+    instance. The event is registered in the constructor and removed by the destructor of that
+    instance. This implementation automatically links the lifetime of an event with the lifetime of
+    the object resposible for it's creation.
+
+    Every event registration is represented by an instance of an event specific class:
 
-    /** \brief Singleton class to manage the event loop
+    \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
+    \li senf::scheduler::EventHook for a special event hook
 
-        This class manages a single select() type event loop. A
-        customer of this class may register any number of file
-        descriptiors with this class and pass callback functions to be
-        called on input, output or error. This functions are specified
-        using boost::function objects
-      */
-    class Scheduler
-        : boost::noncopyable
+    These instance are owned and managed by the user of the scheduler \e not by the scheduler so the
+    RAII concept can be used.
+
+    \code
+    class SomeServer
     {
+        SomeSocketHandle handle_;
+        senf::scheduler::FdEvent event_;
+
     public:
-        ///////////////////////////////////////////////////////////////////////////
-        // Types
+        SomeServer(SomeSocketHandle handle)
+            : handle_ (handle), 
+              event_ ("SomeServer handler", senf::membind(&SomeServer::readData, this),
+                      handle, senf::scheduler::FdEvent::EV_READ)
+        {}
 
-        enum EventId { EV_NONE=0, 
-                       EV_READ=1, EV_PRIO=2, EV_WRITE=4, EV_HUP=8, EV_ERR=16, 
-                       EV_ALL=31 };
+        void readData(int events)
+        {
+            // read data from handle_, check for eof and so on.
+        }
+    };
+    \endcode
 
-        template <class Handle>
-        struct GenericCallback {
-            typedef boost::function<void (typename boost::call_traits<Handle>::param_type,
-                                          EventId) > Callback;
-        };
-       typedef boost::function<void (EventId)> SimpleCallback;
-       typedef boost::function<void ()> TimerCallback;
+    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.
 
-        ///////////////////////////////////////////////////////////////////////////
-        ///\name Structors and default members
-        ///@{
+    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.
 
-        // private default constructor
-        // no copy constructor
-        // no copy assignment
-        // default destructor
-        // no conversion constructors
 
-        static Scheduler & instance();
+    \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.
 
-        template <class Handle>
-        void add(Handle const & handle, 
-                 typename GenericCallback<Handle>::Callback const & cb,
-                 int eventMask = EV_ALL); 
-       template <class Handle>
-        void remove(Handle const & handle, int eventMask = EV_ALL);
+    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
 
-       void timeout(unsigned long timeout, TimerCallback const & cb);
+    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
 
-        void process();
-        void terminate();
+    The handler is identified by an arbitrary, user specified name. This name is used in error
+    messages to identify the failing handler.
 
-    protected:
 
-    private:
-        Scheduler();
-       
-        void do_add(int fd, SimpleCallback const & cb, int eventMask = EV_ALL);
-        void do_remove(int fd, int eventMask = EV_ALL);
+    \section sched_exec Executing the Scheduler
+
+    To enter the scheduler main-loop, call
+    
+    \code
+    senf::scheduler::process();
+    \endcode
+
+    This call will only return in two cases:
 
-       struct EventSpec 
+    \li When a handler calls senf::scheduler::terminate()
+    \li When there is no active file descriptor or timer event.
+
+    Additional <a href="#autotoc-7.">generic functions</a> provide information and %scheduler
+    parameters.
+
+    \section sched_container Event objects and container classes
+
+    As the event objects are \e not copyable, they cannot be placed into ordinary
+    containers. However, it is quite simple to use pointer containers to hold event instances:
+
+    \code
+    #include <boost/ptr_container/ptr_map.hpp>
+    #include <boost/bind.hpp>
+    
+    class Foo
+    {
+    public:
+        void add(int fd)
         {
-            SimpleCallback cb_read;
-            SimpleCallback cb_prio;
-            SimpleCallback cb_write;
-            SimpleCallback cb_hup;
-            SimpleCallback cb_err;
-
-            int epollMask() const;
-        };
-       
-       struct TimerSpec
-       {
-           TimerSpec() : timeout(), cb() {}
-            TimerSpec(unsigned long long timeout_, TimerCallback cb_)
-                : timeout(timeout_), cb(cb_) {}
-
-           bool operator< (TimerSpec const & other) const
-               { return timeout > other.timeout; }
-           
-           unsigned long long timeout;
-           TimerCallback cb;
-       };
-        
-        typedef std::map<int,EventSpec> FdTable;
-       typedef std::priority_queue<TimerSpec> TimerQueue;
+            fdEvents.insert(
+                fd, 
+                new senf::scheduler::FdEvent("foo", boost::bind(&callback, this, fd, _1), fd, 
+                                             senf::scheduler::FdEvent::EV_READ) );
+        }
+
+        void callback(int fd, int events)
+        {
+            FdEvent & event (fdEvents_[fd]);
+
+            // ...
 
-        FdTable fdTable_;
-       TimerQueue timerQueue_;
-        int epollFd_;
-        bool terminate_;
+            if (complete)
+                fdEvents_.remove(fd)
+        }
+
+    private:
+        boost::ptr_map<int, FdEvent> fdEvents_;
     };
+    \endcode
+
+    The pointer container API is (almost) completely identical to the corresponding standard library
+    container API. The only difference is, that all elements added to the container \e must be
+    created via \c new and that the pointer containers themselves are \e not copyable (ok, they are,
+    if the elements are cloneable ...). See <a
+    href="http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/ptr_container.html">Boost.PointerContainer</a>
+    for the pointer container library reference.
+
+    \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 Return timestamp of last event
 
-    int retrieve_filehandle(int fd);
+        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(); 
+
+    /** \brief Return \c true, if any event is registered, \c false otherwise. */
+    bool empty();
+
+    /** \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.
+     */
+    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.ct"
+//#include "Scheduler.cti"
 #endif
 
 \f
 // Local Variables:
 // mode: c++
-// c-file-style: "satcom"
+// fill-column: 100
+// c-file-style: "senf"
+// indent-tabs-mode: nil
+// ispell-local-dictionary: "american"
+// compile-command: "scons -u test"
+// comment-column: 40
 // End: