switch to new MPL based Fraunhofer FOKUS Public License
[senf.git] / senf / Scheduler / FIFORunner.cc
1 // $Id$
2 //
3 // Copyright (C) 2008
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 //
6 // The contents of this file are subject to the Fraunhofer FOKUS Public License
7 // Version 1.0 (the "License"); you may not use this file except in compliance
8 // with the License. You may obtain a copy of the License at 
9 // http://senf.berlios.de/license.html
10 //
11 // The Fraunhofer FOKUS Public License Version 1.0 is based on, 
12 // but modifies the Mozilla Public License Version 1.1.
13 // See the full license text for the amendments.
14 //
15 // Software distributed under the License is distributed on an "AS IS" basis, 
16 // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
17 // for the specific language governing rights and limitations under the License.
18 //
19 // The Original Code is Fraunhofer FOKUS code.
20 //
21 // The Initial Developer of the Original Code is Fraunhofer-Gesellschaft e.V. 
22 // (registered association), Hansastraße 27 c, 80686 Munich, Germany.
23 // All Rights Reserved.
24 //
25 // Contributor(s):
26 //   Stefan Bund <g0dil@berlios.de>
27
28 /** \file
29     \brief FIFORunner non-inline non-template implementation */
30
31 #include "FIFORunner.hh"
32 //#include "FIFORunner.ih"
33
34 // Custom includes
35 #include <signal.h>
36 #include <time.h>
37 #include <cassert>
38 #include <senf/config.hh>
39 #ifdef SENF_BACKTRACE
40     #include <execinfo.h>
41 #endif
42 #include <stdint.h>
43 #include <stdio.h>
44 #include <senf/Utils/Exception.hh>
45 #include "senf/Utils/IgnoreValue.hh"
46 #include <senf/Utils/Console/ScopedDirectory.hh>
47 #include <senf/Utils/Console/ParsedCommand.hh>
48 #include "ConsoleDir.hh"
49
50 //#include "FIFORunner.mpp"
51 #define prefix_
52 //-/////////////////////////////////////////////////////////////////////////////////////////////////
53
54 prefix_ senf::scheduler::detail::FIFORunner::FIFORunner()
55     : tasks_ (), next_ (tasks_.end()), watchdogRunning_ (false), watchdogMs_ (1000),
56       watchdogAbort_ (false), watchdogCount_(0), hangCount_ (0), yield_ (false)
57 {
58     struct sigevent ev;
59     ::memset(&ev, 0, sizeof(ev));
60     ev.sigev_notify = SIGEV_SIGNAL;
61     ev.sigev_signo = SIGURG;
62     ev.sigev_value.sival_ptr = this;
63     if (timer_create(CLOCK_MONOTONIC, &ev, &watchdogId_) < 0)
64         SENF_THROW_SYSTEM_EXCEPTION("timer_create()");
65
66     struct sigaction sa;
67     ::memset(&sa, 0, sizeof(sa));
68     sa.sa_sigaction = &watchdog;
69     sa.sa_flags = SA_SIGINFO;
70     if (sigaction(SIGURG, &sa, 0) < 0)
71         SENF_THROW_SYSTEM_EXCEPTION("sigaction()");
72
73     sigset_t mask;
74     sigemptyset(&mask);
75     sigaddset(&mask, SIGURG);
76     if (sigprocmask(SIG_UNBLOCK, &mask, 0) < 0)
77         SENF_THROW_SYSTEM_EXCEPTION("sigprocmask()");
78
79     tasks_.push_back(highPriorityEnd_);
80     tasks_.push_back(normalPriorityEnd_);
81
82 #ifndef SENF_DISABLE_CONSOLE
83     namespace fty = console::factory;
84     consoleDir().add("abortOnWatchdocTimeout", fty::Command(
85             SENF_MEMBINDFNP( bool, FIFORunner, abortOnTimeout, () const ))
86         .doc("Get current watchdog abort on event status.") );
87     consoleDir().add("abortOnWatchdocTimeout", fty::Command(
88                 SENF_MEMBINDFNP( void, FIFORunner, abortOnTimeout, (bool) ))
89         .doc("Enable/disable abort on watchdog event.") );
90     consoleDir().add("watchdogTimeout", fty::Command(
91             SENF_MEMBINDFNP( unsigned, FIFORunner, taskTimeout, () const ))
92         .doc("Get current watchdog timeout in milliseconds") );
93     consoleDir().add("watchdogTimeout", fty::Command(
94             SENF_MEMBINDFNP( void, FIFORunner, taskTimeout, (unsigned) ))
95         .doc("Set watchdog timeout to in milliseconds\n"
96                 "Setting the watchdog timeout to 0 will disable the watchdog.") );
97     consoleDir().add("watchdogEvents", fty::Command(membind( &FIFORunner::hangCount, this))
98         .doc("Get number of occurred watchdog events.\n"
99                 "Calling this method will reset the counter to 0") );
100 #endif
101 }
102
103 prefix_ senf::scheduler::detail::FIFORunner::~FIFORunner()
104 {
105     timer_delete(watchdogId_);
106     signal(SIGURG, SIG_DFL);
107
108 #ifndef SENF_DISABLE_CONSOLE
109     consoleDir().remove("abortOnWatchdocTimeout");
110     consoleDir().remove("watchdogTimeout");
111     consoleDir().remove("watchdogEvents");
112 #endif
113 }
114
115 prefix_ void senf::scheduler::detail::FIFORunner::startWatchdog()
116 {
117     if (watchdogMs_ > 0) {
118         struct itimerspec timer;
119         ::memset(&timer, 0, sizeof(timer));
120
121         timer.it_interval.tv_sec = watchdogMs_ / 1000;
122         timer.it_interval.tv_nsec = (watchdogMs_ % 1000) * 1000000ul;
123         timer.it_value.tv_sec = timer.it_interval.tv_sec;
124         timer.it_value.tv_nsec = timer.it_interval.tv_nsec;
125
126         if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
127             SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
128
129         watchdogRunning_ = true;
130     }
131     else
132         stopWatchdog();
133 }
134
135 prefix_ void senf::scheduler::detail::FIFORunner::stopWatchdog()
136 {
137     struct itimerspec timer;
138     ::memset(&timer, 0, sizeof(timer));
139
140     if (timer_settime(watchdogId_, 0, &timer, 0) < 0)
141         SENF_THROW_SYSTEM_EXCEPTION("timer_settime()");
142
143     watchdogRunning_ = false;
144 }
145
146 // At the moment, the FIFORunner is not very efficient with many non-runnable tasks since the
147 // complete list of tasks is traversed on each run().
148 //
149 // To optimize this, we would need a way to find the relative ordering of two tasks in O(1) (at the
150 // moment, this is an O(N) operation by traversing the list).
151 //
152 // One idea is, to give each task an 'order' value. Whenever a task is added at the end, it's order
153 // value is set to the order value of the last task + 1. Whenever the order value such added exceeds
154 // some threshold (e.g. 2^31 -1 or some such), the task list is traversed from beginning to end to
155 // assign new consecutive order values. This O(N) operation is so seldom, that it is amortized over
156 // a very long time.
157 //
158 // With this value at hand, we can do several optimizations: One idea would be the following: The
159 // runnable set always has two types of tasks: There are tasks, which are heavily active and are
160 // signaled constantly and other tasks which lie dormant most of the time. Those dormant tasks will
161 // end up at the beginning of the task queue.
162 //
163 // With the above defined 'ordering' field available, we can manage an iterator pointing to the
164 // first and the last runnable task. This will often help a lot since the group of runnable tasks
165 // will mostly be localized to the end of the queue. only occasionally one of the dormant tasks will
166 // be runnable. This additional traversal time will be amortized over a larger time.
167
168 prefix_ void senf::scheduler::detail::FIFORunner::dequeue(TaskInfo * task)
169 {
170     TaskList::iterator i (TaskList::current(*task));
171     if (next_ == i)
172         ++next_;
173     tasks_.erase(i);
174 }
175
176 prefix_ void senf::scheduler::detail::FIFORunner::run()
177 {
178     for (;;) {
179         TaskList::iterator f (tasks_.begin());
180         TaskList::iterator l (TaskList::current(highPriorityEnd_));
181         run(f, l);
182         if (yield_) {
183             yield_ = false;
184             continue;
185         }
186
187         f = l; ++f;
188         l = TaskList::current(normalPriorityEnd_);
189         run(f, l);
190         if (yield_) {
191             yield_ = false;
192             continue;
193         }
194
195         f = l; ++f;
196         l = tasks_.end();
197         run(f, l);
198         if (yield_) {
199             yield_ = false;
200             continue;
201         }
202         break;
203     }
204 }
205
206 prefix_ void senf::scheduler::detail::FIFORunner::run(TaskList::iterator f, TaskList::iterator l)
207 {
208     if (f == l)
209         // We'll have problems inserting NullTask between f and l below, so just explicitly bail out
210         return;
211
212     // This algorithm is carefully adjusted to make it work even when arbitrary tasks are removed
213     // from the queue
214     // - Before we begin, we add a NullTask to the queue. The only purpose of this node is, to mark
215     //   the current end of the queue. The iterator to this node becomes the end iterator of the
216     //   range to process
217     // - We update the TaskInfo and move it to the next queue Element before calling the callback so
218     //   we don't access the TaskInfo if it is removed while the callback is running
219     // - We keep the next to-be-processed node in a class variable which is checked and updated
220     //   whenever a node is removed.
221
222     NullTask null;
223     tasks_.insert(l, null);
224     TaskList::iterator end (TaskList::current(null));
225     next_ = f;
226
227     // Would prefer to use ScopeExit+boost::lambda here instead of try but profiling has shown that
228     // to be to costly here
229
230     try {
231         while (next_ != end) {
232             TaskInfo & task (*next_);
233             if (task.runnable_) {
234                 task.runnable_ = false;
235                 runningName_ = task.name();
236 # ifdef SENF_BACKTRACE
237                 runningBacktrace_ = task.backtrace_;
238 # endif
239                 TaskList::iterator i (next_);
240                 ++ next_;
241                 tasks_.splice(l, tasks_, i);
242                 watchdogCount_ = 1;
243                 yield_ = false;
244                 task.run();
245                 if (yield_)
246                     return;
247             }
248             else
249                 ++ next_;
250         }
251         watchdogCount_ = 0;
252         next_ = l;
253     }
254     catch (...) {
255         watchdogCount_ = 0;
256         next_ = l;
257         throw;
258     }
259 }
260
261 prefix_ senf::scheduler::detail::FIFORunner::TaskList::iterator
262 senf::scheduler::detail::FIFORunner::priorityEnd(TaskInfo::Priority p)
263 {
264     switch (p) {
265     case TaskInfo::PRIORITY_LOW :
266         return tasks_.end();
267     case TaskInfo::PRIORITY_NORMAL :
268         return TaskList::current(normalPriorityEnd_);
269     case TaskInfo::PRIORITY_HIGH :
270         return TaskList::current(highPriorityEnd_);
271     }
272     return tasks_.begin();
273 }
274
275 prefix_ void senf::scheduler::detail::FIFORunner::watchdog(int, siginfo_t * si, void *)
276 {
277     FIFORunner & runner (*static_cast<FIFORunner *>(si->si_value.sival_ptr));
278     if (runner.watchdogCount_ > 0) {
279         ++ runner.watchdogCount_;
280         if (runner.watchdogCount_ > 2) {
281             ++ runner.hangCount_;
282             runner.watchdogError();
283         }
284     }
285 }
286
287 prefix_ void senf::scheduler::detail::FIFORunner::watchdogError()
288 {
289     // We don't care if the write commands below fail, we just give our best to inform the user
290     senf::IGNORE( write(1, "\n\n*** Scheduler task hanging (pid ",34) );
291     static char pid[7];
292     ::snprintf(pid, 7, "%6d", ::getpid());
293     pid[6] = 0;
294     senf::IGNORE( write(1, pid, 6) );
295     senf::IGNORE( write(1, "): ", 3) );
296     senf::IGNORE( write(1, runningName_.c_str(), runningName_.size()) );
297 /*    senf::IGNORE( write(1, " at\n ", 3) );
298 #ifdef SENF_BACKTRACE
299     static char const hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
300                                 'a', 'b', 'c', 'd', 'e', 'f' };
301     static void * entries[SENF_DEBUG_BACKTRACE_NUMCALLERS];
302     int nEntries( ::backtrace(entries, SENF_DEBUG_BACKTRACE_NUMCALLERS) );
303     for (int i=0; i < nEntries; ++i) {
304         senf::IGNORE( write(1, " 0x", 3) );
305         for (unsigned j (sizeof(void*)); j > 0; --j) {
306             uintptr_t v ( reinterpret_cast<uintptr_t>(entries[i]) >> (8*(j-1)) );
307             senf::IGNORE( write(1, &(hex[ (v >> 4) & 0x0f ]), 1) );
308             senf::IGNORE( write(1, &(hex[ (v     ) & 0x0f ]), 1) );
309         }
310     }
311 #endif*/
312     senf::IGNORE( write(1, "\n", 1) );
313
314 #ifdef SENF_BACKTRACE
315     senf::IGNORE( write(1, "Task was initialized at\n", 24) );
316     senf::IGNORE( write(1, runningBacktrace_.c_str(), runningBacktrace_.size()) );
317 #endif
318     senf::IGNORE( write(1, "\n", 1) );
319     if (watchdogAbort_)
320         assert(false);
321 }
322
323 //-/////////////////////////////////////////////////////////////////////////////////////////////////
324 #undef prefix_
325 //#include "FIFORunner.mpp"
326
327
328 // Local Variables:
329 // mode: c++
330 // fill-column: 100
331 // comment-column: 40
332 // c-file-style: "senf"
333 // indent-tabs-mode: nil
334 // ispell-local-dictionary: "american"
335 // compile-command: "scons -u test"
336 // End: