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