-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathnode.cpp
More file actions
488 lines (374 loc) · 11.2 KB
/
node.cpp
File metadata and controls
488 lines (374 loc) · 11.2 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/* Nodes.
*
* Author: Steffen Vogel <post@steffenvogel.de>
* SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University
* SPDX-License-Identifier: Apache-2.0
*/
#include <regex>
#include <openssl/md5.h>
#ifdef __linux__
extern "C" {
#include <sys/socket.h>
#include <sys/types.h>
}
#endif
#include <villas/colors.hpp>
#include <villas/hook.hpp>
#include <villas/hook_list.hpp>
#include <villas/mapping.hpp>
#include <villas/node.hpp>
#include <villas/node/config.hpp>
#include <villas/node/memory.hpp>
#include <villas/node_list.hpp>
#include <villas/path.hpp>
#include <villas/sample.hpp>
#include <villas/signal.hpp>
#include <villas/timing.hpp>
#include <villas/utils.hpp>
#include <villas/uuid.hpp>
#ifdef WITH_NETEM
#include <villas/kernel/if.hpp>
#include <villas/kernel/nl.hpp>
#include <villas/kernel/tc.hpp>
#include <villas/kernel/tc_netem.hpp>
#endif // WITH_NETEM
using namespace villas;
using namespace villas::node;
using namespace villas::utils;
Node::Node(const uuid_t &id, const std::string &name)
: logger(Log::get("node")), sequence_init(0), sequence(0),
in(NodeDirection::Direction::IN, this),
out(NodeDirection::Direction::OUT, this), configPath(),
#ifdef __linux__
fwmark(-1),
#endif // __linux__
#ifdef WITH_NETEM
tc_qdisc(nullptr), tc_classifier(nullptr),
#endif // WITH_NETEM
state(State::INITIALIZED), enabled(true), config(nullptr),
name_short(name), affinity(-1), // all cores
factory(nullptr) {
if (uuid_is_null(id)) {
uuid_generate_random(uuid);
} else {
uuid_copy(uuid, id);
}
if (!name_short.empty()) {
name_long = fmt::format(CLR_RED("{}"), name_short);
} else if (name_short.empty()) {
name_short = "<none>";
name_long = CLR_RED("<none>");
}
}
Node::~Node() {
#ifdef WITH_NETEM
rtnl_qdisc_put(tc_qdisc);
rtnl_cls_put(tc_classifier);
#endif // WITH_NETEM
// Internal loopback nodes have no factory
// Only attempt removal for factories of other node-types.
if (factory != nullptr)
factory->instances.remove(this);
}
int Node::prepare() {
int ret;
ret = in.prepare();
if (ret)
return ret;
ret = out.prepare();
if (ret)
return ret;
state = State::PREPARED;
return 0;
}
int Node::parse(json_t *json) {
assert(state == State::INITIALIZED || state == State::PARSED ||
state == State::CHECKED);
int ret, en = enabled, init_seq = -1;
json_error_t err;
json_t *json_netem = nullptr;
ret = json_unpack_ex(json, &err, 0, "{ s?: b, s?: i }", "enabled", &en,
"initial_sequenceno", &init_seq);
if (ret)
return ret;
if (init_seq >= 0)
sequence_init = init_seq;
#ifdef __linux__
ret = json_unpack_ex(json, &err, 0, "{ s?: { s?: o, s?: i } }", "out",
"netem", &json_netem, "fwmark", &fwmark);
if (ret)
return ret;
#endif // __linux__
enabled = en;
if (json_netem) {
#ifdef WITH_NETEM
int enabled = 1;
ret = json_unpack_ex(json_netem, &err, 0, "{ s?: b }", "enabled", &enabled);
if (ret)
return ret;
if (enabled)
kernel::tc::netem_parse(&tc_qdisc, json_netem);
else
tc_qdisc = nullptr;
#endif // WITH_NETEM
}
struct {
const char *str;
struct NodeDirection *dir;
} dirs[] = {{"in", &in}, {"out", &out}};
const char *fields[] = {"signals", "builtin", "vectorize", "hooks"};
for (unsigned j = 0; j < ARRAY_LEN(dirs); j++) {
json_t *json_dir = json_object_get(json, dirs[j].str);
// Skip if direction is unused
if (!json_dir) {
json_dir = json_pack("{ s: b }", "enabled", 0);
}
// Copy missing fields from main node config to direction config
for (unsigned i = 0; i < ARRAY_LEN(fields); i++) {
json_t *json_field_dir = json_object_get(json_dir, fields[i]);
json_t *json_field_node = json_object_get(json, fields[i]);
if (json_field_node && !json_field_dir)
json_object_set(json_dir, fields[i], json_field_node);
}
ret = dirs[j].dir->parse(json_dir);
if (ret)
return ret;
}
config = json;
return 0;
}
int Node::check() {
assert(state == State::CHECKED || state == State::PARSED ||
state == State::INITIALIZED);
in.check();
out.check();
state = State::CHECKED;
return 0;
}
int Node::start() {
int ret;
assert(state == State::PREPARED);
logger->info("Starting node {}", getNameFull());
ret = in.start();
if (ret)
return ret;
ret = out.start();
if (ret)
return ret;
#ifdef __linux__
// Set fwmark for outgoing packets if netem is enabled for this node
if (fwmark >= 0) {
for (int fd : getNetemFDs()) {
ret = setsockopt(fd, SOL_SOCKET, SO_MARK, &fwmark, sizeof(fwmark));
if (ret)
throw RuntimeError("Failed to set FW mark for outgoing packets");
else
logger->debug("Set FW mark for socket (sd={}) to {}", fd, fwmark);
}
}
#endif // __linux__
state = State::STARTED;
sequence = sequence_init;
return 0;
}
int Node::stop() {
int ret;
if (state != State::STOPPING && state != State::STARTED &&
state != State::CONNECTED && state != State::PENDING_CONNECT)
return 0;
logger->info("Stopping node");
setState(State::STOPPING);
ret = in.stop();
if (ret)
return ret;
ret = out.stop();
if (ret)
return ret;
return 0;
}
int Node::restart() {
int ret;
assert(state == State::STARTED);
logger->info("Restarting node");
ret = stop();
if (ret)
return ret;
ret = start();
if (ret)
return ret;
return 0;
}
int Node::read(struct Sample *smps[], unsigned cnt) {
int toread, readd, nread = 0;
unsigned vect;
if (state == State::PAUSED || state == State::PENDING_CONNECT)
return 0;
else if (state != State::STARTED && state != State::CONNECTED)
return -1;
vect = factory->getVectorize();
if (!vect)
vect = cnt;
while (cnt - nread > 0) {
toread = MIN(cnt - nread, vect);
readd = _read(&smps[nread], toread);
if (readd < 0)
return readd;
nread += readd;
}
#ifdef WITH_HOOKS
// Run read hooks
int rread = in.hooks.process(smps, nread);
if (rread < 0)
return rread;
int skipped = nread - rread;
if (skipped > 0) {
if (stats != nullptr)
stats->update(Stats::Metric::SMPS_SKIPPED, skipped);
logger->trace("Received {} samples of which {} have been skipped", nread,
skipped);
} else
logger->trace("Received {} samples", nread);
return rread;
#else
logger->trace("Received {} samples", nread);
return nread;
#endif // WITH_HOOKS
}
int Node::write(struct Sample *smps[], unsigned cnt) {
int tosend, sent, nsent = 0;
unsigned vect;
if (state == State::PAUSED || state == State::PENDING_CONNECT)
return 0;
else if (state != State::STARTED && state != State::CONNECTED)
return -1;
#ifdef WITH_HOOKS
// Run write hooks
int hook_cnt = out.hooks.process(smps, cnt);
if (hook_cnt <= 0)
return hook_cnt;
cnt = hook_cnt;
#endif // WITH_HOOKS
vect = getFactory()->getVectorize();
if (!vect)
vect = cnt;
while (cnt > static_cast<unsigned>(nsent)) {
tosend = MIN(cnt - nsent, vect);
sent = _write(&smps[nsent], tosend);
if (sent < 0)
return sent;
nsent += sent;
logger->trace("Sent {} samples", sent);
}
return nsent;
}
const std::string &Node::getNameFull() {
if (name_full.empty()) {
auto is1 = getInputSignals(false) ? getInputSignals(false)->size() : 0;
auto is2 = getInputSignals(true) ? getInputSignals(true)->size() : 0;
name_full = fmt::format("{}: uuid={}, #in.signals={}/{}, #in.hooks={}, "
"#out.hooks={}, in.vectorize={}, out.vectorize={}",
getName(), uuid::toString(uuid).c_str(), is1, is2,
in.hooks.size(), out.hooks.size(), in.vectorize,
out.vectorize);
#ifdef WITH_NETEM
name_full += fmt::format(", out.netem={}", tc_qdisc ? "yes" : "no");
if (tc_qdisc)
name_full += fmt::format(", fwmark={}", fwmark);
#endif // WITH_NETEM
if (out.path) {
name_full += fmt::format(
", #out.signals={}/{}",
getOutputSignals(false) ? getOutputSignals(false)->size() : 0,
getOutputSignals() ? getOutputSignals()->size() : 0);
name_full += fmt::format(", out.path={}", out.path->toString());
}
// Append node-type specific details
auto details = getDetails();
if (!details.empty())
name_full += fmt::format(", {}", details);
}
return name_full;
}
SignalList::Ptr Node::getInputSignals(bool after_hooks) const {
return in.getSignals(after_hooks);
}
SignalList::Ptr Node::getOutputSignals(bool after_hooks) const {
if (out.path)
return out.path->getOutputSignals();
return nullptr;
}
unsigned Node::getInputSignalsMaxCount() const {
return in.getSignalsMaxCount();
}
unsigned Node::getOutputSignalsMaxCount() const {
if (out.path)
return out.path->getOutputSignalsMaxCount();
return 0;
}
bool Node::isValidName(const std::string &name) {
std::regex re(RE_NODE_NAME);
return std::regex_match(name, re);
}
json_t *Node::toJson() const {
json_t *json_node;
json_t *json_signals_in = nullptr;
json_t *json_signals_out = nullptr;
json_signals_in = getInputSignals()->toJson();
auto output_signals = getOutputSignals();
if (output_signals)
json_signals_out = output_signals->toJson();
json_node = json_pack(
"{ s: s, s: s, s: s, s: i, s: { s: i, s: o? }, s: { s: i, s: o? } }",
"name", getNameShort().c_str(), "uuid", uuid::toString(uuid).c_str(),
"state", stateToString(state).c_str(), "affinity", affinity, "in",
"vectorize", in.vectorize, "signals", json_signals_in, "out", "vectorize",
out.vectorize, "signals", json_signals_out);
if (stats)
json_object_set_new(json_node, "stats", stats->toJson());
auto *status = _readStatus();
if (status)
json_object_set_new(json_node, "status", status);
/* Add all additional fields of node here.
* This can be used for metadata */
json_object_update(json_node, config);
return json_node;
}
void Node::swapSignals() { SWAP(in.signals, out.signals); }
Node *NodeFactory::make(json_t *json, const uuid_t &id,
const std::string &name) {
int ret;
std::string type;
Node *n;
if (!json_is_object(json))
throw ConfigError(json, "node-config-node",
"Node configuration must be an object");
json_t *json_type = json_object_get(json, "type");
type = json_string_value(json_type);
n = NodeFactory::make(type, id, name);
if (!n)
return nullptr;
ret = n->parse(json);
if (ret) {
delete n;
return nullptr;
}
return n;
}
Node *NodeFactory::make(const std::string &type, const uuid_t &id,
const std::string &name) {
NodeFactory *nf = plugin::registry->lookup<NodeFactory>(type);
if (!nf)
throw RuntimeError("Unknown node-type: {}", type);
return nf->make(id, name);
}
int NodeFactory::start(SuperNode *sn) {
getLogger()->info("Initialized node type which is used by {} nodes",
instances.size());
state = State::STARTED;
return 0;
}
int NodeFactory::stop() {
getLogger()->info("De-initialized node type");
state = State::STOPPED;
return 0;
}