Skip to content

Commit

Permalink
Ska 366 signal handler (#86)
Browse files Browse the repository at this point in the history
* SKA-366: support signal handler

* SKA-366: support signal handler on Windows
  • Loading branch information
VKyllianAubry authored and GitHub Enterprise committed Mar 20, 2024
1 parent 59fe4fa commit eb645c3
Show file tree
Hide file tree
Showing 10 changed files with 308 additions and 25 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
/silkit-qemu-demos-guest.qcow2
/out/
/.vs/
/.vscode/
/build/
/bin/
/lib/
/Downloads/
/_build/
*.build*
*.vector
Expand Down
4 changes: 3 additions & 1 deletion adapter/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@

add_executable(SilKitAdapterQemu
"SilKitAdapterQemu.cpp"
"Parsing.cpp" )
"Parsing.cpp"
"SignalHandler.cpp"
)

target_link_libraries(SilKitAdapterQemu
PRIVATE
Expand Down
210 changes: 210 additions & 0 deletions adapter/SignalHandler.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/* Copyright (c) 2022 Vector Informatik GmbH
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "SignalHandler.hpp"
#include <thread>
#include <stdexcept>
#include <vector>

//forward
namespace {
class SignalMonitor;
} // namespace

// global signal handler
static std::unique_ptr<SignalMonitor> gSignalMonitor;

////////////////////////////////////////////
// Inline Platform Specific Implementations
////////////////////////////////////////////
#if WIN32
#include <windows.h>

namespace {

using namespace adapters;

//forward
BOOL WINAPI systemHandler(DWORD ctrlType);

class SignalMonitor
{
public:
SignalMonitor(SignalHandler handler)
{
_handler = std::move(handler);

auto ok = CreatePipe(&_readEnd, &_writeEnd, nullptr, 0);
if (!ok)
throw std::runtime_error("CreatePipe failed. Cannot create Signal Handler!");
DWORD nowait = PIPE_NOWAIT;
ok = SetNamedPipeHandleState(_writeEnd, &nowait, nullptr, nullptr);
if (!ok)
throw std::runtime_error("Set pipe read end to nonblocking failed. Cannot create Signal Handler!");
SetConsoleCtrlHandler(systemHandler, true);
_worker = std::thread{std::bind(&SignalMonitor::workerMain, this)};
}
~SignalMonitor()
{
SetConsoleCtrlHandler(systemHandler, false);
Notify(-1);
_worker.join();
CloseHandle(_writeEnd);
CloseHandle(_readEnd);
}
void Notify(int signalNumber)
{
// no allocs, no error handling
_signalNumber = signalNumber;
uint8_t buf{};
auto ok = WriteFile(_writeEnd, &buf, sizeof(buf), nullptr, nullptr);
(void)ok;
}

private:
void workerMain()
{
std::vector<uint8_t> buf(1);
//blocking read until Notify() was called
auto ok = ReadFile(_readEnd, buf.data(), static_cast<DWORD>(buf.size()), nullptr, nullptr);
if (!ok)
throw std::runtime_error("SignalMonitor::workerMain: cannot read from pipe.");

if (_handler)
{
_handler(_signalNumber);
}
}
HANDLE _readEnd{INVALID_HANDLE_VALUE}, _writeEnd{INVALID_HANDLE_VALUE};
SignalHandler _handler;
std::thread _worker;
int _signalNumber{-1};
};

BOOL WINAPI systemHandler(DWORD ctrlType)
{
if (gSignalMonitor)
{
gSignalMonitor->Notify(static_cast<int>(ctrlType));
return TRUE;
}
return FALSE;
}

} // end anonymous namespace

#else //UNIX

#include <csignal>
#include <cstring>
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>

namespace {

using namespace adapters;

//forward
void systemHandler(int sigNum);

auto ErrorMessage()
{
return std::string{strerror(errno)};
}

class SignalMonitor
{
public:
SignalMonitor(SignalHandler handler)
{
_handler = std::move(handler);

auto ok = ::pipe(_pipe);
if (ok == -1)
throw std::runtime_error("SignalMonitor: pipe() failed! " + ErrorMessage());
ok = fcntl(_pipe[1], F_SETFL, O_NONBLOCK);
if (ok == -1)
throw std::runtime_error("SignalMonitor: cannot set write end of pipe to non blocking: " + ErrorMessage());

signal(SIGINT, &systemHandler);
signal(SIGTERM, &systemHandler);
_worker = std::thread{std::bind(&SignalMonitor::workerMain, this)};
}

~SignalMonitor()
{
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
Notify(-1);
_worker.join();
::close(_pipe[0]);
::close(_pipe[1]);
}

void Notify(int signalNumber)
{
//in signal handler context: no allocs, no error handling
_signalNumber = signalNumber;
uint8_t buf{};
auto ok = ::write(_pipe[1], &buf, sizeof(buf));
(void)ok;
}

private:
void workerMain()
{
std::vector<uint8_t> buf(1);
//blocking read until Notify() was called
auto ok = ::read(_pipe[0], buf.data(), buf.size());
if (ok == -1)
throw std::runtime_error("SignalMonitor::workerMain: cannot read from pipe: " + ErrorMessage());

if (_handler)
{
_handler(_signalNumber);
}
}

int _pipe[2];
SignalHandler _handler;
std::thread _worker;
int _signalNumber{-1};
};

void systemHandler(int sigNum)
{
if (gSignalMonitor)
{
gSignalMonitor->Notify(sigNum);
}
}

} // namespace
#endif

namespace adapters {

void RegisterSignalHandler(SignalHandler handler)
{
gSignalMonitor.reset(new SignalMonitor(std::move(handler)));
}

} // namespace adapters
32 changes: 32 additions & 0 deletions adapter/SignalHandler.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* Copyright (c) 2022 Vector Informatik GmbH
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include <functional>

namespace adapters {

//! \brief RegisterSignalHandler can be used to portably register a single signal handler.
// It only relies on async-signal-safe C functions internally, but
// it uses a dedicated thread which safely runs the user-provided handler.

using SignalHandler = std::function<void(int)>;
void RegisterSignalHandler(SignalHandler handler);

} // namespace adapters
27 changes: 16 additions & 11 deletions adapter/SilKitAdapterQemu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

#include "Exceptions.hpp"
#include "Parsing.hpp"
#include "SignalHandler.hpp"
#include "../chardev/adapter/ChardevSocketToPubSubAdapter.hpp"
#include "../eth/adapter/EthSocketToEthControllerAdapter.hpp"

Expand All @@ -29,9 +30,19 @@ using namespace std::chrono_literals;
using namespace SilKit::Services::Orchestration;

void promptForExit()
{
std::cout << "Press enter to stop the process..." << std::endl;
std::cin.ignore();
{
std::promise<int> signalPromise;
auto signalValue = signalPromise.get_future();
RegisterSignalHandler([&signalPromise](auto sigNum) {
signalPromise.set_value(sigNum);
});

std::cout << "Press CTRL + C to stop the process..." << std::endl;

signalValue.wait();

std::cout << "\nSignal " << signalValue.get() << " received!" << std::endl;
std::cout << "Exiting..." << std::endl;
}

int main(int argc, char** argv)
Expand Down Expand Up @@ -145,42 +156,36 @@ int main(int argc, char** argv)
auto futureStatus = runningStateFuture.wait_for(15s);
if (futureStatus != std::future_status::ready)
{
std::cout << "Lifecycle Service Stopping: timed out while checking if the participant is currently running.";
promptForExit();
logger->Debug("Lifecycle Service Stopping: timed out while checking if the participant is currently running.");
}

lifecycleService->Stop("Adapter stopped by the user.");

auto finalState = finalStateFuture.wait_for(15s);
if (finalState != std::future_status::ready)
{
std::cout << "Lifecycle service stopping: timed out" << std::endl;
promptForExit();
logger->Debug("Lifecycle service stopping: timed out");
}
}
catch (const SilKit::ConfigurationError& error)
{
std::cerr << "Invalid configuration: " << error.what() << std::endl;
promptForExit();
return CONFIGURATION_ERROR;
}
catch (const InvalidCli&)
{
adapters::print_help();
std::cerr << std::endl << "Invalid command line arguments." << std::endl;
promptForExit();
return CLI_ERROR;
}
catch (const SilKit::SilKitError& error)
{
std::cerr << "SIL Kit runtime error: " << error.what() << std::endl;
promptForExit();
return OTHER_ERROR;
}
catch (const std::exception& error)
{
std::cerr << "Something went wrong: " << error.what() << std::endl;
promptForExit();
return OTHER_ERROR;
}

Expand Down
2 changes: 1 addition & 1 deletion chardev/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ wsl$ ./build/bin/SilKitDemoChardevEchoDevice
Creating participant 'EchoDevice' at silkit://localhost:8501
[2022-08-31 18:07:03.818] [EchoDevice] [info] Creating participant 'EchoDevice' at 'silkit://localhost:8501', SIL Kit version: 4.0.19
[2022-08-31 18:07:03.935] [EchoDevice] [info] Connected to registry at 'tcp://127.0.0.1:8501' via 'tcp://127.0.0.1:49242' (silkit://localhost:8501)
Press enter to stop the process...
Press CTRL + C to stop the process...
...
```

Expand Down
1 change: 1 addition & 0 deletions chardev/demos/SimpleEcho/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
add_executable(SilKitDemoChardevEchoDevice
"SilKitDemoChardevEchoDevice.cpp"
${CMAKE_SOURCE_DIR}/adapter/Parsing.cpp
${CMAKE_SOURCE_DIR}/adapter/SignalHandler.cpp
)
target_link_libraries(SilKitDemoChardevEchoDevice
PRIVATE
Expand Down
Loading

0 comments on commit eb645c3

Please sign in to comment.