-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathsignal_handler.h
77 lines (65 loc) · 2.41 KB
/
signal_handler.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#pragma once
#include <functional>
#include <memory>
#include <thread>
#include <vector>
#include "external/envoy/source/common/common/logger.h"
namespace Nighthawk {
/**
* Callback definition for providing a delegate that should be executed after a signal
* is observed.
*/
using SignalCallback = std::function<void()>;
/**
* Utility class for handling TERM and INT signals. Allows wiring up a callback that
* should be invoked upon signal reception. This callback implementation does not have to be
* signal safe, as a different thread is used to fire it.
* NOTE: Only the first observed signal will result in the callback being invoked.
* WARNING: only a single instance should be active at any given time in a process, and
* the responsibility for not breaking this rule is not enforced at this time.
*
* Example usage:
*
* Process p;
* {
* // Signals will be handled while in this scope.
* // The provided callback will call cancel(), gracefully terminating
* // execution.
* auto s = SignalHandler([&p]() { log("cancelling!"); p->cancel(); });
* p->executeInfinitelyOrUntilCancelled();
* }
*
*/
class SignalHandler final : public Envoy::Logger::Loggable<Envoy::Logger::Id::main> {
public:
/**
* Constructs a new SignalHandler instance.
* WARNING: Only a single instance is allowed to be active process-wide at any given time.
* @param signal_callback will be invoked after the first signal gets caught. Does not need to be
* signal-safe.
*/
SignalHandler(const SignalCallback& signal_callback);
// Not copyable or movable.
SignalHandler(SignalHandler const&) = delete;
void operator=(SignalHandler const&) = delete;
~SignalHandler();
private:
/**
* Fires on signal reception.
*/
void onSignal();
/**
* Notifies the thread responsible for shutting down the server that it is time to do so, if
* needed. Safe to use in signal handling, and non-blocking.
*/
void initiateShutdown();
std::thread shutdown_thread_;
// Signal handling needs to be lean so we can't directly initiate shutdown while handling a
// signal. Therefore we write a bite to a this pipe to propagate signal reception. Subsequently,
// the read side will handle the actual shut down of the gRPC service without having to worry
// about signal-safety.
std::vector<int> pipe_fds_;
bool destructing_{false};
};
using SignalHandlerPtr = std::unique_ptr<SignalHandler>;
} // namespace Nighthawk