1
0
Fork 0
mirror of https://git.rwth-aachen.de/acs/public/villas/node/ synced 2025-03-23 00:00:01 +01:00
VILLASnode/src/villas-pipe.cpp

523 lines
12 KiB
C++
Raw Normal View History

/** Receive messages from server snd print them on stdout.
*
* @file
* @author Steffen Vogel <post@steffenvogel.de>
2022-03-15 09:28:57 -04:00
* @copyright 2014-2022, Institute for Automation of Complex Power Systems, EONERC
2022-07-04 18:20:03 +02:00
* @license Apache 2.0
*********************************************************************************/
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <signal.h>
#include <thread>
2018-07-03 21:04:28 +02:00
#include <iostream>
2018-10-20 14:20:51 +02:00
#include <atomic>
#include <villas/node/config.hpp>
2019-03-26 07:01:10 +01:00
#include <villas/config_helper.hpp>
2018-10-20 14:20:51 +02:00
#include <villas/super_node.hpp>
#include <villas/utils.hpp>
#include <villas/utils.hpp>
2018-10-20 14:20:51 +02:00
#include <villas/log.hpp>
2019-04-23 13:11:08 +02:00
#include <villas/colors.hpp>
#include <villas/node.hpp>
#include <villas/timing.hpp>
#include <villas/pool.hpp>
2021-05-10 00:12:30 +02:00
#include <villas/format.hpp>
2018-10-20 14:20:51 +02:00
#include <villas/kernel/rt.hpp>
#include <villas/exceptions.hpp>
#include <villas/nodes/websocket.hpp>
#include <villas/tool.hpp>
namespace villas {
namespace node {
namespace tools {
2018-07-03 21:51:48 +02:00
2022-01-11 09:10:52 -05:00
class Pipe;
class PipeDirection {
2018-10-20 14:20:51 +02:00
protected:
struct Pool pool;
Node *node;
2021-05-10 00:12:30 +02:00
Format *formatter;
std::thread thread;
2021-02-16 14:15:14 +01:00
Logger logger;
2019-06-05 19:00:09 +02:00
bool stop;
bool enabled;
int limit;
2022-01-11 09:10:52 -05:00
int count;
2018-10-20 14:20:51 +02:00
public:
PipeDirection(Node *n, Format *fmt, bool en, int lim, const std::string &name) :
node(n),
2021-05-10 00:12:30 +02:00
formatter(fmt),
2019-06-05 19:00:09 +02:00
stop(false),
enabled(en),
2022-01-11 09:10:52 -05:00
limit(lim),
count(0)
{
2021-02-16 14:15:14 +01:00
auto loggerName = fmt::format("pipe:{}", name);
logger = logging.get(loggerName);
/* Initialize memory */
unsigned pool_size = LOG2_CEIL(MAX(node->out.vectorize, node->in.vectorize));
int ret = pool_init(&pool, pool_size, SAMPLE_LENGTH(DEFAULT_SAMPLE_LENGTH), node->getMemoryType());
if (ret < 0)
throw RuntimeError("Failed to allocate memory for pool.");
}
~PipeDirection()
{
int ret __attribute__((unused));
ret = pool_destroy(&pool);
}
virtual
void run() = 0;
2018-10-20 14:20:51 +02:00
void startThread()
{
2019-06-05 19:00:09 +02:00
stop = false;
if (enabled)
thread = std::thread(&PipeDirection::run, this);
}
2016-06-26 15:33:04 +02:00
void stopThread()
{
2019-06-05 19:00:09 +02:00
stop = true;
if (enabled) {
2022-01-11 09:10:52 -05:00
// We send a SIGUSR2 to the threads to unblock their blocking read() syscalls
pthread_kill(thread.native_handle(), SIGUSR2);
thread.join();
}
}
};
class PipeSendDirection : public PipeDirection {
2022-01-11 09:10:52 -05:00
friend Pipe;
public:
PipeSendDirection(Node *n, Format *i, bool en = true, int lim = -1) :
2021-02-16 14:15:14 +01:00
PipeDirection(n, i, en, lim, "send")
{ }
virtual
void run()
{
2022-01-11 09:10:52 -05:00
logger->debug("Send thread started");
2021-05-10 00:12:30 +02:00
unsigned last_sequenceno = 0;
2022-01-11 09:10:52 -05:00
int scanned, sent, allocated;
struct Sample *smps[node->out.vectorize];
2022-01-11 09:10:52 -05:00
while (!stop) {
allocated = sample_alloc_many(&pool, smps, node->out.vectorize);
if (allocated < 0)
throw RuntimeError("Failed to get {} samples out of send pool.", node->out.vectorize);
else if (allocated < (int) node->out.vectorize)
logger->warn("Send pool underrun");
2021-05-10 00:12:30 +02:00
scanned = formatter->scan(stdin, smps, allocated);
if (scanned < 0) {
2022-02-24 07:31:00 -05:00
if (!stop)
logger->warn("Failed to read from stdin");
}
/* Fill in missing sequence numbers */
for (int i = 0; i < scanned; i++) {
2019-06-23 16:13:23 +02:00
if (smps[i]->flags & (int) SampleFlags::HAS_SEQUENCE)
last_sequenceno = smps[i]->sequence;
else
smps[i]->sequence = last_sequenceno++;
}
2018-10-20 14:20:51 +02:00
sent = node->write(smps, scanned);
2018-10-20 14:20:51 +02:00
2022-02-24 07:31:00 -05:00
sample_decref_many(smps, allocated);
2022-01-11 09:10:52 -05:00
count += sent;
if (limit > 0 && count >= limit)
2022-02-24 07:31:00 -05:00
goto leave_limit;
if (feof(stdin))
goto leave_eof;
}
2022-02-24 07:31:00 -05:00
goto leave;
2019-06-05 19:00:09 +02:00
2022-02-24 07:31:00 -05:00
leave_eof:
logger->info("Reached end-of-file.");
raise(SIGUSR1);
goto leave;
2022-01-11 09:10:52 -05:00
2022-02-24 07:31:00 -05:00
leave_limit:
logger->info("Reached send limit.");
2022-01-11 09:10:52 -05:00
raise(SIGUSR1);
2022-02-24 07:31:00 -05:00
leave:
2022-01-11 09:10:52 -05:00
logger->debug("Send thread stopped");
}
};
class PipeReceiveDirection : public PipeDirection {
2017-07-24 19:33:35 +02:00
2022-01-11 09:10:52 -05:00
friend Pipe;
public:
PipeReceiveDirection(Node *n, Format *i, bool en = true, int lim = -1) :
2021-02-16 14:15:14 +01:00
PipeDirection(n, i, en, lim, "recv")
{ }
virtual
void run()
{
2022-01-11 09:10:52 -05:00
logger->debug("Receive thread started");
int recv, allocated = 0;
struct Sample *smps[node->in.vectorize];
2019-06-05 19:00:09 +02:00
while (!stop) {
allocated = sample_alloc_many(&pool, smps, node->in.vectorize);
if (allocated < 0)
throw RuntimeError("Failed to allocate {} samples from receive pool.", node->in.vectorize);
else if (allocated < (int) node->in.vectorize)
logger->warn("Receive pool underrun: allocated only {} of {} samples", allocated, node->in.vectorize);
recv = node->read(smps, allocated);
if (recv < 0) {
2022-02-24 07:31:00 -05:00
if (node->getState() == State::STOPPING || stop) {
sample_decref_many(smps, allocated);
goto leave;
2022-02-24 07:31:00 -05:00
}
logger->warn("Failed to receive samples from node {}: reason={}", node->getName(), recv);
2022-03-14 15:33:33 -04:00
} else
formatter->print(stdout, smps, recv);
2022-02-24 07:31:00 -05:00
2021-05-10 00:12:30 +02:00
sample_decref_many(smps, allocated);
2022-02-24 07:31:00 -05:00
count += recv;
if (limit > 0 && count >= limit)
goto leave_limit;
2017-08-05 21:02:09 +02:00
}
2022-02-24 07:31:00 -05:00
goto leave;
leave_limit:
2022-01-11 09:10:52 -05:00
logger->info("Reached receive limit.");
raise(SIGUSR1);
2022-02-24 07:31:00 -05:00
leave:
logger->debug("Receive thread stopped");
}
};
class Pipe : public Tool {
public:
Pipe(int argc, char *argv[]) :
Tool(argc, argv, "pipe"),
stop(false),
2021-05-10 00:12:30 +02:00
formatter(),
timeout(0),
reverse(false),
format("villas.human"),
dtypes("64f"),
2022-01-11 09:10:52 -05:00
config_cli(json_object())
{
2022-01-11 09:10:52 -05:00
send.enabled = true;
send.limit = -1;
recv.enabled = true;
recv.limit = -1;
2017-07-24 19:33:35 +02:00
2022-01-11 09:10:52 -05:00
int ret = memory::init(DEFAULT_NR_HUGEPAGES);
if (ret)
throw RuntimeError("Failed to initialize memory");
}
2016-09-10 22:19:07 -04:00
~Pipe()
{
2021-02-16 14:15:14 +01:00
json_decref(config_cli);
}
protected:
std::atomic<bool> stop;
SuperNode sn; /**< The global configuration */
2021-05-10 00:12:30 +02:00
Format *formatter;
2016-06-26 15:33:04 +02:00
int timeout;
bool reverse;
std::string format;
std::string dtypes;
std::string uri;
std::string nodestr;
2021-02-16 14:15:14 +01:00
json_t *config_cli;
2022-01-11 09:10:52 -05:00
struct {
int limit;
bool enabled;
std::unique_ptr<PipeReceiveDirection> dir;
} recv;
struct {
int limit;
bool enabled;
std::unique_ptr<PipeSendDirection> dir;
} send;
void handler(int signal, siginfo_t *sinfo, void *ctx)
{
2022-01-11 09:10:52 -05:00
logger->debug("Received {} signal.", strsignal(signal));
switch (signal) {
2019-06-05 19:00:09 +02:00
case SIGALRM:
2022-01-11 09:10:52 -05:00
logger->info("Reached timeout.");
stop = true;
break;
2019-06-05 19:00:09 +02:00
case SIGUSR1:
2022-01-11 09:10:52 -05:00
if (recv.dir->enabled) {
if (recv.dir->limit < 0 && feof(stdin))
stop = true;
if (recv.dir->limit > 0 && recv.dir->count >= recv.dir->limit)
stop = true;
}
if (send.dir->enabled && send.dir->limit > 0) {
if (send.dir->count >= send.dir->limit)
stop = true;
}
break;
2019-06-05 19:00:09 +02:00
default:
2022-01-11 09:10:52 -05:00
stop = true;
break;
}
}
void usage()
{
std::cout << "Usage: villas-pipe [OPTIONS] CONFIG NODE" << std::endl
<< " CONFIG path to a configuration file" << std::endl
<< " NODE the name of the node to which samples are sent and received from" << std::endl
<< " OPTIONS are:" << std::endl
<< " -f FMT set the format" << std::endl
<< " -t DT the data-type format string" << std::endl
<< " -o OPTION=VALUE overwrite options in config file" << std::endl
<< " -x swap read / write endpoints" << std::endl
<< " -s only read data from stdin and send it to node" << std::endl
<< " -r only read data from node and write it to stdout" << std::endl
<< " -T NUM terminate after NUM seconds" << std::endl
<< " -L NUM terminate after NUM samples sent" << std::endl
<< " -l NUM terminate after NUM samples received" << std::endl
<< " -h show this usage information" << std::endl
<< " -d set logging level" << std::endl
<< " -V show the version of the tool" << std::endl << std::endl;
printCopyright();
}
void parse()
{
int c, ret;
2019-04-17 18:46:18 +02:00
char *endptr;
while ((c = getopt(argc, argv, "Vhxrsd:l:L:T:f:t:o:")) != -1) {
switch (c) {
case 'V':
printVersion();
2019-04-17 18:46:18 +02:00
exit(EXIT_SUCCESS);
case 'f':
format = optarg;
break;
case 't':
dtypes = optarg;
break;
2019-04-17 18:46:18 +02:00
case 'x':
reverse = true;
break;
2019-04-17 18:46:18 +02:00
case 's':
2022-01-11 09:10:52 -05:00
recv.enabled = false; // send only
2019-04-17 18:46:18 +02:00
break;
2017-08-05 21:02:09 +02:00
2019-04-17 18:46:18 +02:00
case 'r':
2022-01-11 09:10:52 -05:00
send.enabled = false; // receive only
2019-04-17 18:46:18 +02:00
break;
2019-04-17 18:46:18 +02:00
case 'l':
2022-01-11 09:10:52 -05:00
recv.limit = strtoul(optarg, &endptr, 10);
2019-04-17 18:46:18 +02:00
goto check;
2017-08-05 21:02:09 +02:00
2019-04-17 18:46:18 +02:00
case 'L':
2022-01-11 09:10:52 -05:00
send.limit = strtoul(optarg, &endptr, 10);
2019-04-17 18:46:18 +02:00
goto check;
2017-10-18 12:49:52 +02:00
2019-04-17 18:46:18 +02:00
case 'T':
timeout = strtoul(optarg, &endptr, 10);
goto check;
2019-04-17 18:46:18 +02:00
case 'o':
2021-02-16 14:15:14 +01:00
ret = json_object_extend_str(config_cli, optarg);
2019-04-17 18:46:18 +02:00
if (ret)
throw RuntimeError("Invalid option: {}", optarg);
break;
2017-08-05 21:02:09 +02:00
2019-04-17 18:46:18 +02:00
case 'd':
logging.setLevel(optarg);
break;
2018-08-20 18:31:27 +02:00
2019-04-17 18:46:18 +02:00
case 'h':
case '?':
usage();
exit(c == '?' ? EXIT_FAILURE : EXIT_SUCCESS);
}
continue;
2017-08-05 21:02:09 +02:00
2019-04-17 18:46:18 +02:00
check: if (optarg == endptr)
throw RuntimeError("Failed to parse parse option argument '-{} {}'", c, optarg);
}
if (argc != optind + 2) {
usage();
exit(EXIT_FAILURE);
}
uri = argv[optind];
nodestr = argv[optind+1];
}
2019-04-17 18:46:18 +02:00
int main()
{
int ret;
Node *node;
2021-05-10 00:12:30 +02:00
json_t *json_format;
json_error_t err;
2019-04-17 18:46:18 +02:00
logger->info("Logging level: {}", logging.getLevelName());
2019-04-17 18:46:18 +02:00
if (!uri.empty())
2019-04-17 18:46:18 +02:00
sn.parse(uri);
else
logger->warn("No configuration file specified. Starting unconfigured. Use the API to configure this instance.");
2021-05-10 00:12:30 +02:00
/* Try parsing format config as JSON */
json_format = json_loads(format.c_str(), 0, &err);
formatter = json_format
? FormatFactory::make(json_format)
: FormatFactory::make(format);
if (!formatter)
throw RuntimeError("Failed to initialize formatter");
2019-04-17 18:46:18 +02:00
2021-05-10 00:12:30 +02:00
formatter->start(dtypes);
2019-04-17 18:46:18 +02:00
node = sn.getNode(nodestr);
if (!node)
throw RuntimeError("Node {} does not exist!", nodestr);
2016-09-10 22:19:07 -04:00
2022-01-11 09:10:52 -05:00
if (recv.enabled && !(node->getFactory()->getFlags() & (int) NodeFactory::Flags::SUPPORTS_READ))
2020-01-09 10:35:21 +01:00
throw RuntimeError("Node {} can not receive data. Consider using send-only mode by using '-s' option", nodestr);
2022-01-11 09:10:52 -05:00
if (send.enabled && !(node->getFactory()->getFlags() & (int) NodeFactory::Flags::SUPPORTS_WRITE))
throw RuntimeError("Node {} can not send data. Consider using receive-only mode by using '-r' option", nodestr);
2020-01-09 10:35:21 +01:00
#if defined(WITH_NODE_WEBSOCKET) && defined(WITH_WEB)
2019-04-17 18:46:18 +02:00
/* Only start web subsystem if villas-pipe is used with a websocket node */
if (node->getFactory()->getFlags() & (int) NodeFactory::Flags::REQUIRES_WEB) {
2019-04-17 18:46:18 +02:00
Web *w = sn.getWeb();
w->start();
}
#endif /* WITH_NODE_WEBSOCKET */
2019-04-17 18:46:18 +02:00
if (reverse)
node->reverse();
2016-06-08 22:38:21 +02:00
ret = node->getFactory()->start(&sn);
2019-04-17 18:46:18 +02:00
if (ret)
throw RuntimeError("Failed to intialize node type {}: reason={}", node->getFactory()->getName(), ret);
2019-04-17 18:46:18 +02:00
sn.startInterfaces();
2019-01-21 22:59:20 +01:00
ret = node->check();
2019-04-17 18:46:18 +02:00
if (ret)
throw RuntimeError("Invalid node configuration");
2016-06-26 15:33:04 +02:00
ret = node->prepare();
2019-04-17 18:46:18 +02:00
if (ret)
throw RuntimeError("Failed to prepare node {}: reason={}", node->getName(), ret);
2018-08-17 12:40:03 +02:00
ret = node->start();
2019-04-17 18:46:18 +02:00
if (ret)
throw RuntimeError("Failed to start node {}: reason={}", node->getName(), ret);
2016-06-08 22:38:21 +02:00
2022-01-11 09:10:52 -05:00
recv.dir = std::make_unique<PipeReceiveDirection>(node, formatter, recv.enabled, recv.limit);
send.dir = std::make_unique<PipeSendDirection>(node, formatter, send.enabled, send.limit);
2022-01-11 09:10:52 -05:00
recv.dir->startThread();
send.dir->startThread();
2016-06-26 15:33:04 +02:00
2022-01-11 09:10:52 -05:00
/* Arm timeout timer */
2019-04-17 18:46:18 +02:00
alarm(timeout);
2019-04-17 18:46:18 +02:00
while (!stop)
2022-01-11 09:10:52 -05:00
usleep(0.1e6);
2019-04-17 18:46:18 +02:00
2022-01-11 09:10:52 -05:00
/* We are stopping the node here in order to unblock the receiving threads
* Node::read() call and allow it to be joined(). */
ret = node->stop();
2019-04-17 18:46:18 +02:00
if (ret)
throw RuntimeError("Failed to stop node {}: reason={}", node->getName(), ret);
2018-10-20 14:20:51 +02:00
2022-01-11 09:10:52 -05:00
recv.dir->stopThread();
send.dir->stopThread();
2019-04-17 18:46:18 +02:00
sn.stopInterfaces();
2018-10-20 14:20:51 +02:00
ret = node->getFactory()->stop();
2019-04-17 18:46:18 +02:00
if (ret)
throw RuntimeError("Failed to stop node type {}: reason={}", node->getFactory()->getName(), ret);
2019-01-21 22:59:20 +01:00
#if defined(WITH_NODE_WEBSOCKET) && defined(WITH_WEB)
/* Only start web subsystem if villas-pipe is used with a websocket node */
if (node->getFactory()->getFlags() & (int) NodeFactory::Flags::REQUIRES_WEB) {
Web *w = sn.getWeb();
w->stop();
}
#endif /* WITH_NODE_WEBSOCKET */
2021-05-10 00:12:30 +02:00
delete formatter;
2018-10-20 14:20:51 +02:00
2019-04-17 18:46:18 +02:00
return 0;
}
};
2018-10-20 14:20:51 +02:00
} // namespace tools
} // namespace node
} // namespace villas
int main(int argc, char *argv[])
{
2019-06-18 17:52:54 +02:00
villas::node::tools::Pipe t(argc, argv);
return t.run();
}