Socket: Add a 'facet<>()' member to access protocol-facets from generic socket handles
[senf.git] / Scheduler / ClockService.hh
1 // $Id$
2 //
3 // Copyright (C) 2007
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 ClockService public header */
25
26 #ifndef HH_ClockService_
27 #define HH_ClockService_ 1
28
29 // Custom includes
30 #include <sys/time.h> 
31 #include <boost/utility.hpp>
32 #include <boost/date_time/posix_time/posix_time.hpp>
33 #include <boost/scoped_ptr.hpp>
34 #include "../Utils/singleton.hh"
35
36 //#include "ClockService.mpp"
37 ///////////////////////////////hh.p////////////////////////////////////////
38
39 namespace senf {
40
41 #ifndef DOXYGEN
42     namespace detail { class ClockServiceTest; }
43 #endif
44
45     // Implementation note:
46     //
47     // The clock value is represented as a 64bit unsigned integer number of nanosecods elapsed since
48     // the construction of the ClockService object. 
49     // 
50     // The implementation must provide two features:
51     // a) It must reliably detect clock changes
52     // b) In case of a clock change a reasonably accurate fallback clock value must be provided
53     //
54     // We do this using setitimer/getitimer. We setup an interval timer sending SIGALRM whenever
55     // CheckInverval seconds have elapsed.
56     //
57     // On every SIGALRM signal we save the current value of gettimeofday(). If this new value is
58     // substantially different from the currently saved value + CheckInterval, the clock has been
59     // changed.
60     //
61     // Whenever the current clock value is requested using now(), the current gettimeofday() value
62     // is compared with the saved value. If the difference is substantially more than CheckInterval,
63     // the clock has been changed.
64     //
65     // This provides clock skew detection. If clock skew is detected, we need to move base_ by the
66     // amount the time has been changed. To do this we need an as accurate as possible approximation
67     // of the expected current time value. We need to differentiate two cases:
68     //
69     // a) Clock skew detected within now()
70     //
71     // In this case, we use getitimer() to find the time remaining in the timer. Using this value
72     // and the saved gettimeofday() value we can adjust base_ accordingly.
73     //
74     // b) Clock skew detected in the signal handler
75     //
76     // In this case we use the saved gettimeofday() value + CheckInterval to adjust base_.
77     
78     /** \brief Reliable high precision monotonous clock source
79
80         The ClockService provides a highly accurate monotonous clock source based on
81         gettimeofday(). However, it takes additional precautions to detect clock skew.
82
83         \implementation We use a mix of static and non-static members to achieve high performance
84             in the normal case (no clock skew) and still encapsulate the dependency on legacy C
85             headers. Using the senf::singleton mixin ensures, that the instance is constructed
86             before main even when instance() is not called.
87       */
88     class ClockService
89         : singleton<ClockService>
90     {
91     public:
92         ///////////////////////////////////////////////////////////////////////////
93         // Types
94
95         /** \brief ClockService timer data type
96             
97             Unsigned integer type representing scheduler time. Scheduler time is measured in
98             nanoseconds relative to some implementation defined reference time.
99          */
100         typedef boost::int_fast64_t clock_type;
101
102         /** \brief Absolute time data type
103
104             Boost.DateTime datatype used to represent absolute date/time values.
105          */
106         typedef boost::posix_time::ptime abstime_type;
107
108         static unsigned const CheckInterval = 10;
109
110         ///////////////////////////////////////////////////////////////////////////
111         ///\name Structors and default members
112         ///@{
113
114         ~ClockService();
115
116         ///@}
117         ///////////////////////////////////////////////////////////////////////////
118
119         static clock_type now();  ///< Return current clock value
120         
121         static abstime_type abstime(clock_type clock); ///< Convert clock to absolute time
122                                         /**< This member converts a clock value into an absolute
123                                              Boost.DateTime value.
124                                              \note You should not base timeout calculations on this
125                                                  absolute time value. Clock time is guaranteed to be
126                                                  monotonous, absolute time may be non-monotonous if
127                                                  the system date/time is changed. */
128
129         static clock_type clock(abstime_type time); ///< Convert absolute time to clock value
130                                         /**< This member converst an absolute time value into the
131                                              corresponding clock value.
132                                              \see abstime */
133
134         static clock_type from_time_t(time_t const & time); 
135                                         ///< Convert legacy time_t to clock value
136                                         /**< This member converts an absolute time value 
137                                              represented as a time_t value into a clock value */
138
139         static clock_type from_timeval(timeval const & time); 
140                                         ///< Convert legacy timeval to clock value
141                                         /**< This member converts an absolute time value
142                                              represented as a timeval value into a clock value */
143
144         static clock_type nanoseconds(clock_type v);
145         static clock_type microseconds(clock_type v);
146         static clock_type milliseconds(clock_type v);
147         static clock_type seconds(clock_type v);
148         static clock_type minutes(clock_type v);
149         static clock_type hours(clock_type v);
150         static clock_type days(clock_type v);
151
152         static void restart();
153
154     private:
155         ClockService();
156
157         void timer();
158
159         clock_type now_m();
160         abstime_type abstime_m(clock_type clock);
161         clock_type clock_m(abstime_type time);
162         void restart_m(bool restart = true);
163
164         bool checkSkew(boost::posix_time::ptime time);
165         void updateSkew(boost::posix_time::ptime time);
166         void clockSkew(boost::posix_time::ptime time, boost::posix_time::ptime expected);
167
168         void restartTimer(bool restart = true);
169
170         boost::posix_time::ptime base_;
171         boost::posix_time::ptime heartbeat_;
172
173         // I don't want this header to depend on the legacy C headers.
174         /// Internal: ClockService private data (PIMPL idiom)
175         struct Impl;
176         boost::scoped_ptr<Impl> impl_;
177
178         friend class Impl;
179 #ifndef DOXYGEN
180         friend class senf::detail::ClockServiceTest;
181         friend class singleton<ClockService>;
182 #endif
183     };
184
185 }
186
187 ///////////////////////////////hh.e////////////////////////////////////////
188 #include "ClockService.cci"
189 //#include "ClockService.ct"
190 //#include "ClockService.cti"
191 #endif
192
193 \f
194 // Local Variables:
195 // mode: c++
196 // fill-column: 100
197 // comment-column: 40
198 // c-file-style: "senf"
199 // indent-tabs-mode: nil
200 // ispell-local-dictionary: "american"
201 // compile-command: "scons -u test"
202 // End: