8#include <framework/pcore/ProcessMonitor.h>
9#include <framework/core/EventProcessor.h>
10#include <framework/pcore/GlobalProcHandler.h>
12#include <framework/pcore/zmq/messages/ZMQMessageFactory.h>
13#include <framework/pcore/zmq/messages/ZMQDefinitions.h>
25 const std::string& controlSocketAddress)
28 B2DEBUG(30,
"ProcessMonitor starting.....");
35 zmq::context_t context(1);
39 getcwd(currentdir, 256);
41 zmq::socket_t pubSocket(context, ZMQ_XPUB);
44 pubSocket.bind(subSocketAddress);
45 }
catch (zmq::error_t& err) {
46 B2DEBUG(30,
"ZMQ bind error!! " + std::string(err.what()));
49 pubSocket.set(zmq::sockopt::linger, 0);
51 zmq::socket_t subSocket(context, ZMQ_XSUB);
53 subSocket.bind(pubSocketAddress);
54 subSocket.set(zmq::sockopt::linger, 0);
56 zmq::socket_t controlSocket(context, ZMQ_SUB);
57 controlSocket.bind(controlSocketAddress);
58 controlSocket.set(zmq::sockopt::linger, 0);
59 controlSocket.set(zmq::sockopt::subscribe,
"");
61 B2DEBUG(30,
"Will now start the proxy..");
65 zmq::socket_ref nullsocket;
66 zmq::proxy_steerable(pubSocket, subSocket, nullsocket, controlSocket);
68 }
catch (zmq::error_t& ex) {
69 if (ex.num() != EINTR) {
70 B2ERROR(
"There was an error during the proxy event: " << ex.what());
75 controlSocket.close();
79 B2DEBUG(30,
"Proxy has finished");
84 std::this_thread::sleep_for(std::chrono::milliseconds(500));
87 m_client.
initialize<ZMQ_PUB>(pubSocketAddress, subSocketAddress, controlSocketAddress,
false);
93 B2DEBUG(30,
"Started multicast publishing on " << pubSocketAddress <<
" and subscribing on " << subSocketAddress);
112 B2DEBUG(30,
"Try to kill the processes gently...");
119 const auto multicastAnswer = [
this](
const auto & socket) {
123 B2DEBUG(30,
"Process pid " << pair.first <<
" of type " <<
static_cast<char>(pair.second) <<
" is still alive");
130 bool allProcessesStopped =
true;
133 allProcessesStopped =
false;
138 if (not allProcessesStopped) {
139 B2DEBUG(30,
"Start waiting for processes to go down.");
141 B2DEBUG(30,
"Finished waiting for processes to go down.");
146 B2DEBUG(30,
"Will kill the proxy now.");
150 std::this_thread::sleep_for(std::chrono::milliseconds(10));
160 const auto multicastAnswer = [
this](
const auto & socket) {
166 if (not pullResult) {
167 B2ERROR(
"Input process did not start properly!");
176 const auto multicastAnswer = [
this](
const auto & socket) {
182 if (not pullResult) {
183 B2ERROR(
"Worker process did not start properly!");
192 const auto multicastAnswer = [
this](
const auto & socket) {
198 if (not pullResult) {
199 B2ERROR(
"Output process did not start properly!");
216 const auto multicastAnswer = [
this](
const auto & socket) {
223template <
class ASocket>
226 auto pcbMulticastMessage = ZMQMessageFactory::fromSocket<ZMQNoIdMessage>(socket);
227 if (pcbMulticastMessage->isMessage(EMessageTypes::c_helloMessage)) {
228 const int pid = std::stoi(pcbMulticastMessage->getData());
234 }
else if (pcbMulticastMessage->isMessage(EMessageTypes::c_goodbyeMessage)) {
235 const int pid = std::stoi(pcbMulticastMessage->getData());
238 B2WARNING(
"An unknown PID died!");
241 const ProcType procType = processIt->second;
250 }
else if (pcbMulticastMessage->isMessage(EMessageTypes::c_killWorkerMessage)) {
251 const int workerPID = atoi(pcbMulticastMessage->getData().c_str());
252 B2DEBUG(30,
"Got message to kill worker " << workerPID);
253 if (kill(workerPID, SIGKILL) == 0) {
254 B2WARNING(
"Needed to kill worker " << workerPID <<
" as it was requested.");
256 B2ERROR(
"Try to kill process " << workerPID <<
", but process is already gone.");
259 }
else if (pcbMulticastMessage->isMessage(EMessageTypes::c_statisticMessage)) {
261 B2DEBUG(30,
"Having received the process statistics");
276 const auto& pair = *iter;
278 B2ASSERT(
"This pid should not be in our list!", pair.first != 0);
280 if (std::find(currentProcessList.begin(), currentProcessList.end(), pair.first) != currentProcessList.end()) {
287 B2ERROR(
"An input process has died unexpected! Need to go down.");
291 B2ERROR(
"An output process has died unexpected! Need to go down.");
295 B2ERROR(
"A proxy process has died unexpected! Need to go down.");
300 B2ERROR(
"A worker process has died unexpectedly.");
305 B2DEBUG(30,
"An children process has died expectedly.");
331 B2DEBUG(30,
"No input and no output process around. Will go home now!");
337 if (g_signalReceived > 0) {
338 B2DEBUG(30,
"Received signal " << g_signalReceived);
356 if (neededWorkers < 0) {
357 B2FATAL(
"Something went completely wrong here! I have more workers as requested...");
359 if (neededWorkers > 0) {
360 B2DEBUG(30,
"I need to restart " << neededWorkers <<
" workers");
362 return static_cast<unsigned int>(neededWorkers);
367 auto correctProcType = [&procType](
const auto & pair) {
368 return pair.second == procType;
static void installMainSignalHandlers(void(*fn)(int)=nullptr)
Install signal handler for INT, TERM and QUIT signals.
static ProcType getProcType(int pid)
Return the proc type of this process.
static const std::vector< int > & getPIDList()
Return the PID list handled by the running GlobalProcHandler. This PID list is updated using the sign...
static bool isProcess(ProcType procType)
Return true if the process is of type procType.
static bool startProxyProcess()
Fork and initialize a proxy process.
static void killAllProcesses()
Hard kill all processes.
void processMulticast(const ASocket &socket)
Process a message from the multicast.
bool m_hasEnded
Someone requested us to end the processing.
StreamHelper m_streamer
The data store streamer.
std::map< int, ProcType > m_processList
The current list of pid -> process types (to be compared to the proc handler)
void checkMulticast(int timeout=0)
check multicast for messages and kill workers if requested
void waitForRunningWorker(int timeout)
Block until either the worker process is running or the timeout (in seconds) is raised.
bool hasEnded() const
If we have received a SIGINT signal or the last process is gone, we can end smoothly.
void checkSignals(int g_signalReceived)
check if we have received any signal from the user or OS. Kill the processes if not SIGINT.
void waitForRunningInput(int timeout)
Block until either the input process is running or the timeout (in seconds) is raised.
void checkChildProcesses()
check the child processes, if one has died
bool m_receivedStatistics
Did we already receive the statistics?
void terminate()
Terminate the processing.
unsigned int m_requestedNumberOfWorkers
How many workers we should request to start.
void waitForRunningOutput(int timeout)
Block until either the output process is running or the timeout (in seconds) is raised.
void subscribe(const std::string &pubSocketAddress, const std::string &subSocketAddress, const std::string &controlSocketAddress)
Start listening for process management information on the given address.
bool hasWorkers() const
Check if there is at least one running worker.
void killProcesses(unsigned int timeout)
Ask all processes to terminate. If not, kill them after timeout seconds.
unsigned int processesWithType(const ProcType &procType) const
Cound the number of processes with a certain type.
ZMQClient m_client
The client used for message processing.
void initialize(unsigned int requestedNumberOfWorkers)
Init the processing with that many workers.
unsigned int needMoreWorkers() const
Compare our current list of workers of how many we want to have.
void reset()
Reset the internal state.
void read(std::unique_ptr< ZMQNoIdMessage > message)
Read in a ZMQ message and rebuilt the data store from it.
void initialize(int compressionLevel, bool handleMergeable)
Initialize this class. Call this e.g. in the first event.
bool isOnline() const
Check if the client was initialized and not terminated.
void publish(AZMQMessage message) const
Publish the message to the multicast.
void initialize(const std::string &pubSocketAddress, const std::string &subSocketAddress, const std::string &socketAddress, bool bind)
Initialize the multicast and a data socket of the given type.
void terminate(bool sendGoodbye=true)
Terminate the sockets properly.
void reset()
Reset the sockets. ATTENTION: this does not close the sockets! Use only after forks to not clean up t...
void send(AZMQMessage message) const
Send a message over the data socket.
void subscribe(EMessageTypes messageType)
Subscribe to the given multicast message type.
static auto createMessage(const std::string &msgIdentity, const EMessageTypes msgType, const std::unique_ptr< EvtMessage > &eventMessage)
Create an ID Message out of an identity, the type and an event message.
static zmq::message_t createZMQMessage(zmq::message_t message)
Just pass a zmq message.
ProcType
Type of the process used for storing and mapping the child processes in the process handler.
int pollMulticast(unsigned int timeout, AMulticastAnswer multicastAnswer) const
Poll method to only the multicast socket.
@ c_Proxy
Multicast Proxy Process.
@ c_Output
Output Process.
@ c_Worker
Worker/Reconstruction Process.
@ c_Monitor
Monitoring Process.
@ c_Stopped
The process is stopped/killed.
@ c_Init
Before the forks, the process is in init state.
Abstract base class for different kinds of events.