jaulib v1.3.8
Jau Support Library (C++, Java, ..)
Loading...
Searching...
No Matches
service_runner.cpp
Go to the documentation of this file.
1/*
2 * Author: Sven Gothel <sgothel@jausoft.com>
3 * Copyright (c) 2022 Gothel Software e.K.
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be
14 * included in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 */
24
26
27extern "C" {
28 #include <unistd.h>
29 #include <sys/socket.h>
30 #include <poll.h>
31 #include <signal.h>
32 #include <pthread.h>
33}
34
35#include <jau/debug.hpp>
36
37#include <jau/basic_algos.hpp>
38#include <jau/secmem.hpp>
39#include <jau/os/os_support.hpp>
40
41using namespace jau;
42
43void service_runner::service_thread() {
44 {
45 const std::lock_guard<std::mutex> lock(mtx_lifecycle); // RAII-style acquire and relinquish via destructor
46 try {
47 service_init_locked(*this);
48 running = true;
49 DBG_PRINT("%s::worker Started", name_.c_str());
50 } catch(const std::exception &e) {
51 thread_id_ = 0;
52 running = false;
53 ERR_PRINT2("%s::worker Exception @ service_init_locked: %s", name_.c_str(), e.what());
54 }
55 }
56 cv_init.notify_all(); // have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
57
58 if( !running ) {
59 return;
60 }
61
62 thread_local jau::call_on_release thread_cleanup([&]() {
63 DBG_PRINT("%s::worker::ThreadCleanup: serviceRunning %d -> 0", name_.c_str(), running.load());
64 running = false;
65 cv_init.notify_all();
66 });
67
68 while( !shall_stop_ ) {
69 try {
70 service_work(*this);
71 } catch(const std::exception &e) {
72 shall_stop_ = true;
73 ERR_PRINT2("%s::worker Exception @ service_work: %s", name_.c_str(), e.what());
74 }
75 }
76 {
77 const std::lock_guard<std::mutex> lock(mtx_lifecycle); // RAII-style acquire and relinquish via destructor
78 WORDY_PRINT("%s::worker: Ended", name_.c_str());
79 try {
80 service_end_locked(*this);
81 } catch(const std::exception &e) {
82 ERR_PRINT2("%s::worker Exception @ service_end_locked: %s", name_.c_str(), e.what());
83 }
84 thread_id_ = 0;
85 running = false;
86 thread_cleanup.set_released();
87 }
88 cv_init.notify_all(); // have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
89}
90
91const ::pid_t service_runner::pid_self = ::getpid();
92
93static void sigaction_handler(int sig, siginfo_t *info, void *ucontext) noexcept {
94 bool pidMatch = info->si_pid == service_runner::pid_self;
95 WORDY_PRINT("service_runner.sigaction: sig %d, info[code %d, errno %d, signo %d, pid %d, uid %d], pid-self %d (match %d)",
96 sig, info->si_code, info->si_errno, info->si_signo,
97 info->si_pid, info->si_uid,
98 service_runner::pid_self, pidMatch);
99 (void)ucontext;
100
101 if( !pidMatch || SIGALRM != sig ) {
102 return;
103 }
104#if 0
105 // We do not de-install the handler on single use,
106 // as we act for multiple SIGALRM events within direct-bt
107 remove_sighandler();
108#endif
109}
110
111bool service_runner::install_sighandler() noexcept {
112 struct sigaction sa_setup;
113 jau::zero_bytes_sec(&sa_setup, sizeof(sa_setup));
114 sa_setup.sa_sigaction = sigaction_handler;
115 ::sigemptyset(&(sa_setup.sa_mask));
116 sa_setup.sa_flags = SA_SIGINFO;
117 if( 0 != ::sigaction( SIGALRM, &sa_setup, nullptr ) ) {
118 ERR_PRINT("service_runner::install_sighandler: Setting sighandler");
119 return false;
120 }
121 DBG_PRINT("service_runner::install_sighandler: OK");
122 return true;
123}
124
126 struct sigaction sa_setup;
127 jau::zero_bytes_sec(&sa_setup, sizeof(sa_setup));
128 sa_setup.sa_handler = SIG_DFL;
129 ::sigemptyset(&(sa_setup.sa_mask));
130 sa_setup.sa_flags = 0;
131 if( 0 != ::sigaction( SIGALRM, &sa_setup, nullptr ) ) {
132 ERR_PRINT("service_runner::remove_sighandler: Resetting sighandler");
133 return false;
134 }
135 DBG_PRINT("service_runner::remove_sighandler: OK");
136 return true;
137}
138
141 Callback service_work_,
142 Callback service_init_locked_,
143 Callback service_end_locked_) noexcept
144: name_( std::move(name__) ),
145 service_shutdown_timeout_( service_shutdown_timeout ),
146 service_work( std::move(service_work_) ),
147 service_init_locked( std::move(service_init_locked_) ),
148 service_end_locked( std::move(service_end_locked_) ),
149 shall_stop_(true), running(false),
150 thread_id_(0)
151{
152 DBG_PRINT("%s::ctor", name_.c_str());
153}
154
156 DBG_PRINT("%s::dtor: Begin", name_.c_str());
157 stop();
158 DBG_PRINT("%s::dtor: End", name_.c_str());
159}
160
162 {
163 const std::lock_guard<std::mutex> lock_stop(mtx_shall_stop_); // RAII-style acquire and relinquish via destructor
164 shall_stop_ = true;
165 }
166 cv_shall_stop_.notify_all(); // have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
167}
168
169void service_runner::start() noexcept {
170 DBG_PRINT("%s::start: Begin: %s", name_.c_str(), toString().c_str());
171 /**
172 * We utilize a global SIGALRM handler, since we only can install one handler.
173 */
174 std::unique_lock<std::mutex> lock(mtx_lifecycle); // RAII-style acquire and relinquish via destructor
175 {
176 const std::lock_guard<std::mutex> lock_stop(mtx_shall_stop_); // RAII-style acquire and relinquish via destructor
177 shall_stop_ = false;
178 }
179 cv_shall_stop_.notify_all(); // have mutex unlocked before notify_all to avoid pessimistic re-block of notified wait() thread.
180
181 if( running ) {
182 DBG_PRINT("%s::start: End.0: %s", name_.c_str(), toString().c_str());
183 return;
184 }
185
186 std::thread t(&service_runner::service_thread, this); // @suppress("Invalid arguments")
187 thread_id_ = t.native_handle();
188 // Avoid 'terminate called without an active exception'
189 // as t may end due to I/O errors.
190 t.detach();
191
192 while( false == running && false == shall_stop_ ) {
193 cv_init.wait(lock);
194 }
195 DBG_PRINT("%s::start: End.X: %s", name_.c_str(), toString().c_str());
196}
197
198bool service_runner::stop() noexcept {
199 DBG_PRINT("%s::stop: Begin: %s", name_.c_str(), toString().c_str());
200
201 std::unique_lock<std::mutex> lock(mtx_lifecycle); // RAII-style acquire and relinquish via destructor
202 const ::pthread_t tid_service = thread_id_;
203 const bool is_service = tid_service == ::pthread_self();
204 DBG_PRINT("%s::stop: service[running %d, shall_stop %d, is_service %d, tid %p)",
205 name_.c_str(), running.load(), shall_stop_.load(), is_service, (void*)tid_service); // NOLINT(performance-no-int-to-ptr)
207 bool result;
208 if( running ) {
209 if( !is_service ) {
210 if( 0 != tid_service ) {
211 #if JAU_OS_HAS_PTHREAD
212 if constexpr ( jau::os::has_pthread() ) {
213 int kerr;
214 if( 0 != ( kerr = ::pthread_kill(tid_service, SIGALRM) ) ) {
215 ERR_PRINT("%s::stop: pthread_kill %p FAILED: %d", name_.c_str(), (void*)tid_service, kerr); // NOLINT(performance-no-int-to-ptr)
216 }
217 } else
218 #endif
219 {
220 INFO_PRINT("%s::stop: pthread_kill n/a, service %p running", name_.c_str(), (void*)tid_service); // NOLINT(performance-no-int-to-ptr)
221 }
222 }
223 // Ensure the reader thread has ended, no runaway-thread using *this instance after destruction
224 result = true;
225 const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(service_shutdown_timeout_);
226 while( true == running && result ) {
227 std::cv_status s { std::cv_status::no_timeout };
228 if( fractions_i64::zero < service_shutdown_timeout_ ) {
229 s = wait_until(cv_init, lock, timeout_time );
230 } else {
231 cv_init.wait(lock);
232 }
233 if( std::cv_status::timeout == s && true == running ) {
234 ERR_PRINT("%s::stop: Timeout (force !running): %s", name_.c_str(), toString().c_str());
235 result = false; // bail out w/ false
236 }
237 }
238 } else {
239 // is_service
240 result = false; // initiated, but not stopped yet
241 }
242 } else {
243 result = true;
244 }
245 DBG_PRINT("%s::stop: End: Result %d, %s", name_.c_str(), result, toString().c_str());
246 return result;
247}
248
249bool service_runner::join() noexcept {
250 DBG_PRINT("%s::join: Begin: %s", name_.c_str(), toString().c_str());
251 std::unique_lock<std::mutex> lock(mtx_lifecycle); // RAII-style acquire and relinquish via destructor
252
253 const bool is_service = thread_id_ == ::pthread_self();
254 DBG_PRINT("%s::join: is_service %d, %s", name_.c_str(), is_service, toString().c_str());
255 bool result;
256 if( running ) {
257 if( !is_service ) {
258 // Ensure the reader thread has ended, no runaway-thread using *this instance after destruction
259 result = true;
260 const fraction_timespec timeout_time = getMonotonicTime() + fraction_timespec(service_shutdown_timeout_);
261 while( true == running && result ) {
262 std::cv_status s { std::cv_status::no_timeout };
263 if( fractions_i64::zero < service_shutdown_timeout_ ) {
264 s = wait_until(cv_init, lock, timeout_time );
265 } else {
266 cv_init.wait(lock);
267 }
268 if( std::cv_status::timeout == s && true == running ) {
269 ERR_PRINT("%s::join: Timeout (force !running): %s", name_.c_str(), toString().c_str());
270 result = false; // bail out w/ false
271 }
272 }
273 } else {
274 // is_service
275 result = false;
276 }
277 } else {
278 result = true;
279 }
280 DBG_PRINT("%s::join: End: Result %d, %s", name_.c_str(), result, toString().c_str());
281 return result;
282}
283
284std::string service_runner::toString() const noexcept {
285 return "ServiceRunner["+name_+", running "+std::to_string(is_running())+", shall_stop "+std::to_string(shall_stop_)+
286 ", thread_id "+to_hexstring((void*)thread_id_)+"]"; // NOLINT(performance-no-int-to-ptr)
287}
bool stop() noexcept
Stops this service, if running.
function< void(service_runner_ref)> Callback
static bool remove_sighandler() noexcept
Remove the sighandler.
fraction_i64 service_shutdown_timeout() const noexcept
Returns maximum duration in fractions of seconds to wait for service to stop at stop() and join(),...
void set_shall_stop() noexcept
Marks the service thread to stop in due process by flagging shall stop to true.
service_runner(std::string name, fraction_i64 service_shutdown_timeout, Callback service_work, Callback service_init_locked=Callback(), Callback service_end_locked=Callback()) noexcept
Service runner constructor.
bool is_running() const noexcept
Returns true if service is running.
static const ::pid_t pid_self
bool join() noexcept
Blocks the current thread until service is stopped or returns immediately if not running or called fr...
std::string toString() const noexcept
Returns a string representation of this service.
~service_runner() noexcept
Service runner destructor.
void start() noexcept
Starts this service, if not running already.
#define ERR_PRINT(...)
Use for unconditional error messages, prefix '[elapsed_time] Error @ FILE:LINE FUNC: '.
Definition debug.hpp:112
#define WORDY_PRINT(...)
Use for environment-variable environment::VERBOSE conditional verbose messages, prefix '[elapsed_time...
Definition debug.hpp:71
#define DBG_PRINT(...)
Use for environment-variable environment::DEBUG conditional debug messages, prefix '[elapsed_time] De...
Definition debug.hpp:52
#define ERR_PRINT2(...)
Use for unconditional error messages, prefix '[elapsed_time] Error @ FILE:LINE FUNC: '.
Definition debug.hpp:115
fraction_timespec getMonotonicTime() noexcept
Returns current monotonic time since Unix Epoch 00:00:00 UTC on 1970-01-01.
fraction< int64_t > fraction_i64
fraction using int64_t as integral type
constexpr bool has_pthread() noexcept
Evaluates true if platform supports posix compatible threading.
void zero_bytes_sec(void *s, size_t n) noexcept __attrdecl_no_optimize__
Wrapper to ::explicit_bzero(), ::bzero() or ::memset(), whichever is available in that order.
std::string to_hexstring(value_type const &v, const bool skipLeading0x=false) noexcept
Produce a lower-case hexadecimal string representation with leading 0x in MSB of the given pointer.
constexpr const jau::fraction_i64 zero(0l, 1lu)
zero is 0/1
__pack(...): Produces MSVC, clang and gcc compatible lead-in and -out macros.
Definition backtrace.hpp:32
void INFO_PRINT(const char *format,...) noexcept
Use for unconditional informal messages, prefix '[elapsed_time] Info: '.
Definition debug.cpp:248
std::cv_status wait_until(std::condition_variable &cv, std::unique_lock< std::mutex > &lock, const fraction_timespec &absolute_time, const bool monotonic=true) noexcept
wait_until causes the current thread to block until the condition variable is notified,...
static void sigaction_handler(int sig, siginfo_t *info, void *ucontext) noexcept
Timespec structure using int64_t for its components in analogy to struct timespec_t on 64-bit platfor...