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