Goby3 3.7.0
2026.11.12
Loading...
Searching...
No Matches
pubsub_test.h
Go to the documentation of this file.
1// Copyright 2026:
2// GobySoft, LLC (2013-)
3// Community contributors (see AUTHORS file)
4// File authors:
5// Toby Schneider <toby@gobysoft.org>
6//
7//
8// This file is part of the Goby Underwater Autonomy Project Libraries
9// ("The Goby Libraries").
10//
11// The Goby Libraries are free software: you can redistribute them and/or modify
12// them under the terms of the GNU Lesser General Public License as published by
13// the Free Software Foundation, either version 2.1 of the License, or
14// (at your option) any later version.
15//
16// The Goby Libraries are distributed in the hope that they will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19// GNU Lesser General Public License for more details.
20//
21// You should have received a copy of the GNU Lesser General Public License
22// along with Goby. If not, see <http://www.gnu.org/licenses/>.
23
24#ifndef GOBY_MIDDLEWARE_TOOL_PUBSUB_TEST_H
25#define GOBY_MIDDLEWARE_TOOL_PUBSUB_TEST_H
26
27#include <chrono>
28#include <cstdlib>
29#include <functional>
30#include <iomanip>
31#include <map>
32#include <memory>
33#include <regex>
34#include <set>
35#include <sstream>
36#include <string>
37#include <vector>
38
39#include <google/protobuf/dynamic_message.h>
40#include <google/protobuf/io/tokenizer.h>
41#include <google/protobuf/text_format.h>
42#include <google/protobuf/util/json_util.h>
43
44#include <boost/units/systems/si.hpp>
45
46#include "dccl/dynamic_protobuf_manager.h"
47
48#include "goby/exception.h"
62
63namespace goby
64{
65namespace middleware
66{
67namespace tool
68{
71{
72 std::string endpoint;
73 std::vector<unsigned char> bytes;
74 int scheme;
75 std::string type;
76 std::string group;
77};
78
81{
82 public:
83 using Clock = std::chrono::steady_clock;
84 using MessageHandler = std::function<void(const PubSubTestMessage&)>;
85
86 virtual ~PubSubTestEndpoint() = default;
87
88 virtual const std::string& name() const = 0;
89 virtual bool intervehicle() const { return false; }
90 virtual void publish(const protobuf::PubSubTestPublish& pub) = 0;
91 virtual void publish_health_request() = 0;
92 virtual void subscribe_all(MessageHandler handler) = 0;
95 virtual void arm(const protobuf::PubSubTestExpect&) {}
96 virtual void ready() = 0;
97 virtual bool hold_state() = 0;
98 virtual void poll(std::chrono::milliseconds wait) = 0;
99};
100
102template <typename Portal, typename PortalConfig>
104{
105 public:
106 PubSubTestPortalEndpoint(std::string name, const PortalConfig& cfg, std::string tool_name)
107 : name_(std::move(name)), tool_name_(std::move(tool_name)), portal_(cfg)
108 {
109 }
110
111 const std::string& name() const override { return name_; }
112
113 void publish(const protobuf::PubSubTestPublish& pub) override
114 {
115 publish_tool_impl(portal_, pub, tool_name_);
116 }
117
119 {
120 portal_.template publish<groups::health_request>(protobuf::HealthRequest());
121 }
122
123 void subscribe_all(MessageHandler handler) override
124 {
125 portal_.subscribe_regex([this, handler](const std::vector<unsigned char>& bytes, int scheme,
126 const std::string& type, const Group& group)
127 { handler({name_, bytes, scheme, type, std::string(group)}); },
128 {MarshallingScheme::ALL_SCHEMES}, ".*", ".*");
129 }
130
131 void ready() override { portal_.ready(); }
132 bool hold_state() override { return portal_.hold_state(); }
133 void poll(std::chrono::milliseconds wait) override { portal_.poll(wait); }
134
135 private:
136 std::string name_;
137 std::string tool_name_;
138 Portal portal_;
139};
140
141namespace detail
142{
144inline bool parse_intervehicle_group(const std::string& s, std::uint32_t& group)
145{
146 static const std::regex number("[0-9]+");
147 if (!std::regex_match(s, number))
148 return false;
149 try
150 {
151 const auto value = std::stoull(s);
152 if (value >= Group::invalid_numeric_group)
153 return false;
154 group = static_cast<std::uint32_t>(value);
155 return true;
156 }
157 catch (const std::exception&)
158 {
159 return false;
160 }
161}
162
164inline const google::protobuf::FieldDescriptor*
165group_field_descriptor(const google::protobuf::Descriptor* desc, const std::string& name)
166{
167 using google::protobuf::FieldDescriptor;
168 const auto* field = desc->FindFieldByName(name);
169 if (!field || field->is_repeated())
170 return nullptr;
171 switch (field->cpp_type())
172 {
173 case FieldDescriptor::CPPTYPE_INT32:
174 case FieldDescriptor::CPPTYPE_INT64:
175 case FieldDescriptor::CPPTYPE_UINT32:
176 case FieldDescriptor::CPPTYPE_UINT64: return field;
177 default: return nullptr;
178 }
179}
180
181inline void set_group_field(google::protobuf::Message& msg,
182 const google::protobuf::FieldDescriptor* field, std::uint32_t group)
183{
184 using google::protobuf::FieldDescriptor;
185 const auto* refl = msg.GetReflection();
186 switch (field->cpp_type())
187 {
188 case FieldDescriptor::CPPTYPE_INT32: refl->SetInt32(&msg, field, group); break;
189 case FieldDescriptor::CPPTYPE_INT64: refl->SetInt64(&msg, field, group); break;
190 case FieldDescriptor::CPPTYPE_UINT32: refl->SetUInt32(&msg, field, group); break;
191 case FieldDescriptor::CPPTYPE_UINT64: refl->SetUInt64(&msg, field, group); break;
192 default: break;
193 }
194}
195
196inline std::uint32_t get_group_field(const google::protobuf::Message& msg,
197 const google::protobuf::FieldDescriptor* field)
198{
199 using google::protobuf::FieldDescriptor;
200 const auto* refl = msg.GetReflection();
201 switch (field->cpp_type())
202 {
203 case FieldDescriptor::CPPTYPE_INT32: return refl->GetInt32(msg, field);
204 case FieldDescriptor::CPPTYPE_INT64: return refl->GetInt64(msg, field);
205 case FieldDescriptor::CPPTYPE_UINT32: return refl->GetUInt32(msg, field);
206 case FieldDescriptor::CPPTYPE_UINT64: return refl->GetUInt64(msg, field);
207 default: return Group::invalid_numeric_group;
208 }
209}
210} // namespace detail
211
212namespace detail
213{
214inline std::string json_scalar_to_string(const nlohmann::json& j)
215{
216 return j.is_string() ? j.get<std::string>() : j.dump();
217}
218
219inline bool json_is_numeric(const nlohmann::json& j, double& d)
220{
221 if (j.is_number())
222 {
223 d = j.get<double>();
224 return true;
225 }
226 if (j.is_string())
227 {
228 const std::string s = j.get<std::string>();
229 char* end = nullptr;
230 d = std::strtod(s.c_str(), &end);
231 return !s.empty() && end && *end == '\0';
232 }
233 return false;
234}
235
237inline const nlohmann::json* json_lookup(const nlohmann::json& root, const std::string& path)
238{
239 static const std::regex token_regex("([^.\\[\\]]+)|\\[([0-9]+)\\]");
240 const nlohmann::json* cur = &root;
241 for (auto it = std::sregex_iterator(path.begin(), path.end(), token_regex);
242 it != std::sregex_iterator(); ++it)
243 {
244 if ((*it)[1].matched)
245 {
246 if (!cur->is_object() || !cur->contains((*it)[1].str()))
247 return nullptr;
248 cur = &(*cur)[(*it)[1].str()];
249 }
250 else
251 {
252 const auto idx = std::stoul((*it)[2].str());
253 if (!cur->is_array() || idx >= cur->size())
254 return nullptr;
255 cur = &(*cur)[idx];
256 }
257 }
258 return cur;
259}
260
262inline bool json_subset(const nlohmann::json& expected, const nlohmann::json& actual,
263 const std::string& path, std::string& why)
264{
265 if (expected.is_object())
266 {
267 if (!actual.is_object())
268 {
269 why = path + ": expected an object";
270 return false;
271 }
272 for (auto it = expected.begin(); it != expected.end(); ++it)
273 {
274 const std::string child = path.empty() ? it.key() : path + "." + it.key();
275 if (!actual.contains(it.key()))
276 {
277 why = child + ": missing";
278 return false;
279 }
280 if (!json_subset(it.value(), actual[it.key()], child, why))
281 return false;
282 }
283 return true;
284 }
285
286 double a, b;
287 const bool equal = (json_is_numeric(expected, a) && json_is_numeric(actual, b))
288 ? a == b
289 : json_scalar_to_string(expected) == json_scalar_to_string(actual);
290 if (!equal)
291 why = path + ": expected " + expected.dump() + ", got " + actual.dump();
292 return equal;
293}
294
295inline bool evaluate_condition(const protobuf::PubSubTestCondition& cond, const nlohmann::json& msg,
296 std::string& why)
297{
298 using Op = protobuf::PubSubTestCondition;
299 const nlohmann::json* value = json_lookup(msg, cond.field());
300
301 if (cond.op() == Op::EXISTS || cond.op() == Op::ABSENT)
302 {
303 const bool exists = value != nullptr;
304 if (exists != (cond.op() == Op::EXISTS))
305 why = cond.field() + (exists ? ": present" : ": absent");
306 return exists == (cond.op() == Op::EXISTS);
307 }
308
309 if (!value)
310 {
311 why = cond.field() + ": absent";
312 return false;
313 }
314
315 const std::string actual = json_scalar_to_string(*value);
316 bool ok = false;
317 switch (cond.op())
318 {
319 case Op::REGEX: ok = std::regex_match(actual, std::regex(cond.value())); break;
320 case Op::EXISTS:
321 case Op::ABSENT: break;
322 default:
323 {
324 double a, b;
325 const bool numeric =
326 json_is_numeric(*value, a) && json_is_numeric(nlohmann::json(cond.value()), b);
327 const int cmp = numeric ? (a < b ? -1 : (a > b ? 1 : 0)) : actual.compare(cond.value());
328 switch (cond.op())
329 {
330 case Op::EQ: ok = cmp == 0; break;
331 case Op::NE: ok = cmp != 0; break;
332 case Op::LT: ok = cmp < 0; break;
333 case Op::LE: ok = cmp <= 0; break;
334 case Op::GT: ok = cmp > 0; break;
335 case Op::GE: ok = cmp >= 0; break;
336 default: break;
337 }
338 }
339 }
340 if (!ok)
341 why = cond.field() + " " + Op::Op_Name(cond.op()) + " " + cond.value() + ": got " + actual;
342 return ok;
343}
344
346inline bool protobuf_partial_match(const google::protobuf::Message& expected,
347 const google::protobuf::Message& actual, const std::string& path,
348 std::string& why)
349{
350 using google::protobuf::FieldDescriptor;
351 const auto* refl = expected.GetReflection();
352 const auto* actual_refl = actual.GetReflection();
353 std::vector<const FieldDescriptor*> fields;
354 refl->ListFields(expected, &fields);
355
356 for (const auto* field : fields)
357 {
358 const std::string child = path.empty() ? field->name() : path + "." + field->name();
359 if (field->is_repeated())
360 {
361 const int n = refl->FieldSize(expected, field);
362 if (actual_refl->FieldSize(actual, field) != n)
363 {
364 why = child + ": expected " + std::to_string(n) + " elements, got " +
365 std::to_string(actual_refl->FieldSize(actual, field));
366 return false;
367 }
368 for (int i = 0; i < n; ++i)
369 {
370 const std::string elem = child + "[" + std::to_string(i) + "]";
371 if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
372 {
373 if (!protobuf_partial_match(refl->GetRepeatedMessage(expected, field, i),
374 actual_refl->GetRepeatedMessage(actual, field, i),
375 elem, why))
376 return false;
377 }
378 else
379 {
380 std::string e, a;
381 google::protobuf::TextFormat::PrintFieldValueToString(expected, field, i, &e);
382 google::protobuf::TextFormat::PrintFieldValueToString(actual, field, i, &a);
383 if (e != a)
384 {
385 why = elem + ": expected " + e + ", got " + a;
386 return false;
387 }
388 }
389 }
390 }
391 else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
392 {
393 if (!actual_refl->HasField(actual, field))
394 {
395 why = child + ": missing";
396 return false;
397 }
398 if (!protobuf_partial_match(refl->GetMessage(expected, field),
399 actual_refl->GetMessage(actual, field), child, why))
400 return false;
401 }
402 else
403 {
404 if (!actual_refl->HasField(actual, field))
405 {
406 why = child + ": missing";
407 return false;
408 }
409 std::string e, a;
410 google::protobuf::TextFormat::PrintFieldValueToString(expected, field, -1, &e);
411 google::protobuf::TextFormat::PrintFieldValueToString(actual, field, -1, &a);
412 if (e != a)
413 {
414 why = child + ": expected " + e + ", got " + a;
415 return false;
416 }
417 }
418 }
419 return true;
420}
421
422inline double seconds_since(PubSubTestEndpoint::Clock::time_point start)
423{
424 return std::chrono::duration<double>(PubSubTestEndpoint::Clock::now() - start).count();
425}
426
427inline PubSubTestEndpoint::Clock::duration to_duration(double seconds)
428{
429 return std::chrono::duration_cast<PubSubTestEndpoint::Clock::duration>(
430 std::chrono::duration<double>(seconds));
431}
432
434inline void parse_type_spec(const protobuf::PubSubTestExpect& expect, std::set<int>& schemes,
435 std::string& type_regex)
436{
437 const std::string& spec = expect.type();
438 const auto slash = spec.find('/');
439 if (slash != std::string::npos && slash > 0)
440 {
441 schemes = {MarshallingScheme::from_string(spec.substr(0, slash))};
442 type_regex = spec.substr(slash + 1);
443 }
444 else
445 {
446 schemes = expect.has_scheme()
447 ? std::set<int>{MarshallingScheme::from_string(expect.scheme())}
448 : std::set<int>{MarshallingScheme::ALL_SCHEMES};
449 type_regex = spec;
450 }
451}
452
455inline bool is_intervehicle_report(const protobuf::PubSubTestExpect& expect)
456{
457 std::set<int> schemes;
458 std::string type;
459 parse_type_spec(expect, schemes, type);
460 return schemes == std::set<int>{MarshallingScheme::PROTOBUF} &&
463}
464} // namespace detail
465
473template <typename Portal, typename PortalConfig>
475{
476 public:
477 PubSubTestInterVehicleEndpoint(std::string name, const PortalConfig& cfg)
478 : name_(std::move(name)), portal_(cfg), intervehicle_(portal_)
479 {
480 }
481
482 const std::string& name() const override { return name_; }
483 bool intervehicle() const override { return true; }
484
485 void publish(const protobuf::PubSubTestPublish& pub) override
486 {
487 int scheme = 0;
488 std::string type;
489 parse_publish_type(pub.type(), scheme, type);
491 throw goby::Exception("intervehicle endpoint '" + name_ +
492 "' only publishes DCCL types (DCCL/<type>)");
493
494 std::shared_ptr<google::protobuf::Message> msg =
495 dccl::DynamicProtobufManager::new_protobuf_message<
496 std::shared_ptr<google::protobuf::Message>>(type);
497 if (!google::protobuf::TextFormat::ParseFromString(pub.value(), msg.get()))
498 throw goby::Exception("value does not parse as " + type);
499
500 const auto group = numeric_group(pub.group());
501 const auto* field = group_field(msg->GetDescriptor(), pub.group_field(), group);
502
504 *cfg.mutable_intervehicle() = pub.intervehicle();
505
506 using PublisherType = Publisher<google::protobuf::Message>;
507 PublisherType::set_group_func_type set_group;
508 if (field)
509 set_group = [field](google::protobuf::Message& m, const Group& g)
510 { detail::set_group_field(m, field, g.numeric()); };
511
512 auto report = [this, group_name = pub.group()](const google::protobuf::Message& md)
513 {
514 if (!handler_)
515 return;
516 const std::string bytes = md.SerializeAsString();
517 handler_({name_, std::vector<unsigned char>(bytes.begin(), bytes.end()),
518 MarshallingScheme::PROTOBUF, md.GetDescriptor()->full_name(), group_name});
519 };
520 PublisherType::acked_func_type acked;
521 // an acked_func makes the Publisher require acks, so set one only when asked to
522 if (pub.intervehicle().buffer().ack_required())
523 acked = [report](const google::protobuf::Message&,
524 const intervehicle::protobuf::AckData& ack) { report(ack); };
525 PublisherType::expired_func_type expired =
526 [report](const google::protobuf::Message&,
527 const intervehicle::protobuf::ExpireData& expire) { report(expire); };
528
529 intervehicle_.template publish_dynamic<google::protobuf::Message, MarshallingScheme::DCCL>(
530 std::shared_ptr<const google::protobuf::Message>(msg), DynamicGroup(pub.group(), group),
531 PublisherType(cfg, set_group, acked, expired));
532 }
533
535 {
536 portal_.template publish<groups::health_request>(protobuf::HealthRequest());
537 }
538
539 // only health traffic is taken from the portal: everything else on this endpoint arrives over
540 // the intervehicle layer
541 void subscribe_all(MessageHandler handler) override
542 {
543 handler_ = handler;
544 const std::string health_groups = "^(" + std::string(groups::health_response) + "|" +
545 std::string(groups::health_report) + ")$";
546 portal_.subscribe_regex([this](const std::vector<unsigned char>& bytes, int scheme,
547 const std::string& type, const Group& group)
548 { handler_({name_, bytes, scheme, type, std::string(group)}); },
549 {MarshallingScheme::PROTOBUF}, ".*", health_groups);
550 }
551
552 void arm(const protobuf::PubSubTestExpect& exp) override
553 {
554 if (detail::is_intervehicle_report(exp))
555 return;
556
557 std::set<int> schemes;
558 std::string type;
559 detail::parse_type_spec(exp, schemes, type);
560 const auto* desc = dccl::DynamicProtobufManager::find_descriptor(type);
561 if (!desc)
562 throw goby::Exception("intervehicle endpoint '" + name_ + "': unknown type '" + type +
563 "'");
564
565 const auto group = numeric_group(exp.group());
566 const auto* field = group_field(desc, exp.group_field(), group);
567
568 // an identical subscription is already in place; repeating it would re-forward it
569 const std::string key = type + "/" + std::to_string(group) + "/" + exp.group_field() + "/" +
570 exp.intervehicle().SerializeAsString();
571 if (!armed_.insert(key).second)
572 return;
573
575 *cfg.mutable_intervehicle() = exp.intervehicle();
577 if (field)
578 group_func = [field](const google::protobuf::Message& m)
579 { return Group(detail::get_group_field(m, field)); };
580
581 intervehicle_.subscribe_dynamic(
582 [this, type, group](std::shared_ptr<const google::protobuf::Message> msg)
583 {
584 if (!handler_)
585 return;
587 MarshallingScheme::DCCL>::serialize(*msg);
588 handler_({name_, std::vector<unsigned char>(bytes.begin(), bytes.end()),
589 MarshallingScheme::DCCL, type, std::to_string(group)});
590 },
592 }
593
594 void ready() override { portal_.ready(); }
595 bool hold_state() override { return portal_.hold_state(); }
596 void poll(std::chrono::milliseconds wait) override { intervehicle_.poll(wait); }
597
598 private:
599 std::uint32_t numeric_group(const std::string& s) const
600 {
601 std::uint32_t group;
602 if (!detail::parse_intervehicle_group(s, group))
603 throw goby::Exception("intervehicle endpoint '" + name_ + "': group '" + s +
604 "' is not a numeric group");
605 return group;
606 }
607
608 const google::protobuf::FieldDescriptor* group_field(const google::protobuf::Descriptor* desc,
609 const std::string& name,
610 std::uint32_t group) const
611 {
612 if (name.empty())
613 {
615 throw goby::Exception("intervehicle endpoint '" + name_ + "': group " +
616 std::to_string(group) + " needs a group_field");
617 return nullptr;
618 }
619 const auto* field = detail::group_field_descriptor(desc, name);
620 if (!field)
621 throw goby::Exception("intervehicle endpoint '" + name_ + "': '" + name +
622 "' is not a top-level integer field of " + desc->full_name());
623 return field;
624 }
625
626 std::string name_;
627 Portal portal_;
628 InterVehicleForwarder<Portal> intervehicle_;
629 MessageHandler handler_;
630 std::set<std::string> armed_;
631};
632
633namespace detail
634{
635inline void walk_strings(google::protobuf::Message& msg, const std::string& path,
636 const std::function<void(std::string&, const std::string&)>& f)
637{
638 using google::protobuf::FieldDescriptor;
639 const auto* refl = msg.GetReflection();
640 std::vector<const FieldDescriptor*> fields;
641 refl->ListFields(msg, &fields);
642 for (const auto* field : fields)
643 {
644 const std::string fpath = path.empty() ? field->name() : path + "." + field->name();
645 if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING)
646 {
647 if (field->is_repeated())
648 {
649 for (int i = 0, n = refl->FieldSize(msg, field); i < n; ++i)
650 {
651 std::string s = refl->GetRepeatedString(msg, field, i);
652 f(s, fpath + "[" + std::to_string(i) + "]");
653 refl->SetRepeatedString(&msg, field, i, s);
654 }
655 }
656 else
657 {
658 std::string s = refl->GetString(msg, field);
659 f(s, fpath);
660 refl->SetString(&msg, field, s);
661 }
662 }
663 else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE)
664 {
665 if (field->is_repeated())
666 for (int i = 0, n = refl->FieldSize(msg, field); i < n; ++i)
667 walk_strings(*refl->MutableRepeatedMessage(&msg, field, i),
668 fpath + "[" + std::to_string(i) + "]", f);
669 else
670 walk_strings(*refl->MutableMessage(&msg, field), fpath, f);
671 }
672 }
673}
674
676inline std::string substitute(const std::string& s, const std::map<std::string, std::string>& vars)
677{
678 static const std::regex var("^\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}");
679 std::string out;
680 for (std::size_t i = 0; i < s.size();)
681 {
682 if (s.compare(i, 3, "$${") == 0)
683 {
684 out += "$${";
685 i += 3;
686 continue;
687 }
688 std::smatch m;
689 const std::string tail = s.substr(i, 256);
690 if (s[i] == '$' && std::regex_search(tail, m, var))
691 {
692 auto it = vars.find(m[1].str());
693 if (it != vars.end())
694 {
695 out += it->second;
696 i += m[0].length();
697 continue;
698 }
699 }
700 out += s[i++];
701 }
702 return out;
703}
704} // namespace detail
705
710inline void expand_runs(protobuf::PubSubTest& test, std::vector<protobuf::PubSubTestIssue>& issues)
711{
713 for (int i = 0, n = test.run_size(); i < n; ++i)
714 {
715 const auto& run = test.run(i);
716 if (run.repeat() == 0)
717 {
719 issue.set_location("test.run[" + std::to_string(i) + "].repeat");
720 issue.set_message("must be at least 1");
721 issues.push_back(issue);
722 continue;
723 }
724
725 std::vector<std::map<std::string, std::string>> entries;
726 for (const auto& p : run.for_each())
727 {
728 entries.emplace_back();
729 for (const auto& v : p.var()) entries.back()[v.key()] = v.value();
730 }
731 if (entries.empty())
732 entries.emplace_back();
733
734 const unsigned total = entries.size() * run.repeat();
735 const bool name_varies = run.name().find("${") != std::string::npos;
736 unsigned pass = 0;
737 for (const auto& entry : entries)
738 {
739 for (unsigned r = 0; r < run.repeat(); ++r)
740 {
741 ++pass;
742 auto& copy = *out.Add();
743 copy = run;
744 copy.clear_repeat();
745 copy.clear_for_each();
746 auto vars = entry;
747 vars["ITERATION"] = std::to_string(pass);
748 detail::walk_strings(copy, "", [&vars](std::string& s, const std::string&)
749 { s = detail::substitute(s, vars); });
750 if (total > 1 && !name_varies)
751 copy.set_name((run.name().empty() ? "" : run.name() + " ") + "[" +
752 std::to_string(pass) + "/" + std::to_string(total) + "]");
753 }
754 }
755 }
756 test.mutable_run()->Swap(&out);
757}
758
761inline void find_unresolved_variables(google::protobuf::Message& msg, const std::string& prefix,
762 std::vector<protobuf::PubSubTestIssue>& issues,
763 const std::set<std::string>& allowed = {})
764{
765 static const std::regex var("\\$\\{([A-Za-z_][A-Za-z0-9_]*)");
766 detail::walk_strings(
767 msg, prefix,
768 [&issues, &allowed](std::string& s, const std::string& path)
769 {
770 for (auto it = std::sregex_iterator(s.begin(), s.end(), var);
771 it != std::sregex_iterator(); ++it)
772 {
773 if ((it->position() > 0 && s[it->position() - 1] == '$') ||
774 allowed.count((*it)[1].str()))
775 continue;
777 issue.set_location(path);
778 issue.set_message(
779 "variable '" + (*it)[1].str() +
780 "' is not set (use --define, the environment, a ${NAME:-default}, "
781 "or a run's for_each)");
782 issues.push_back(issue);
783 }
784 });
785}
786
789{
790 detail::walk_strings(msg, "",
791 [](std::string& s, const std::string&)
792 {
793 std::string::size_type pos = 0;
794 while ((pos = s.find("$${", pos)) != std::string::npos)
795 {
796 s.erase(pos, 1);
797 pos += 2;
798 }
799 });
800}
801
806{
807 public:
808 using Issues = std::vector<protobuf::PubSubTestIssue>;
809
810 PubSubTestValidator(const protobuf::PubSubTest& test, std::set<std::string> endpoint_names,
811 std::string prefix = "test")
812 : test_(test), endpoints_(std::move(endpoint_names)), prefix_(std::move(prefix))
813 {
814 }
815
819 std::string default_endpoint)
820 {
821 intervehicle_endpoints_ = std::move(names);
822 default_endpoint_ = std::move(default_endpoint);
823 return *this;
824 }
825
827 {
828 issues_.clear();
829 if (endpoints_.empty())
830 add("endpoint", "no endpoints are declared");
831
832 if (test_.default_timeout() <= 0)
833 add(prefix_ + ".default_timeout", "must be greater than zero");
834 if (test_.connect_timeout() <= 0)
835 add(prefix_ + ".connect_timeout", "must be greater than zero");
836
837 for (int i = 0, n = test_.require_app_size(); i < n; ++i)
838 {
839 const auto& req = test_.require_app(i);
840 const std::string loc = index(prefix_ + ".require_app", i);
841 check_endpoint(loc, req.endpoint());
842 if (req.name_size() == 0)
843 add(loc + ".name", "at least one application name is required");
844 if (req.timeout() <= 0)
845 add(loc + ".timeout", "must be greater than zero");
846 if (req.request_interval() <= 0)
847 add(loc + ".request_interval", "must be greater than zero");
848 }
849
850 for (int i = 0, n = test_.run_size(); i < n; ++i)
851 {
852 const auto& run = test_.run(i);
853 const std::string loc = index(prefix_ + ".run", i);
854 if (run.step_size() > 0 &&
855 (run.publish_size() > 0 || run.expect_size() > 0 || run.has_wait()))
856 add(loc, "a run has either steps or its own publish/expect/wait, not both");
857 check_leaf(loc, run.publish(), run.expect(), run.has_timeout(), run.timeout(),
858 run.wait());
859 for (int j = 0, m = run.step_size(); j < m; ++j)
860 {
861 const auto& step = run.step(j);
862 check_leaf(index(loc + ".step", j), step.publish(), step.expect(),
863 step.has_timeout(), step.timeout(), step.wait());
864 }
865 }
866 return issues_;
867 }
868
869 private:
870 class CollectingErrorCollector : public google::protobuf::io::ErrorCollector
871 {
872 public:
873 void AddError(int line, int column, const std::string& message) override
874 {
875 errors.push_back("column " + std::to_string(column + 1) + ": " + message);
876 }
877 void AddWarning(int, int, const std::string&) override {}
878 std::vector<std::string> errors;
879 };
880
881 static std::string index(const std::string& base, int i)
882 {
883 return base + "[" + std::to_string(i) + "]";
884 }
885
886 void add(const std::string& location, const std::string& message)
887 {
888 protobuf::PubSubTestIssue issue;
889 issue.set_location(location);
890 issue.set_message(message);
891 issues_.push_back(issue);
892 }
893
894 void check_endpoint(const std::string& loc, const std::string& name)
895 {
896 if (!name.empty() && !endpoints_.count(name))
897 add(loc + ".endpoint", "unknown endpoint '" + name + "'");
898 }
899
900 void check_regex(const std::string& loc, const std::string& regex)
901 {
902 try
903 {
904 std::regex r(regex);
905 }
906 catch (const std::regex_error& e)
907 {
908 add(loc, "invalid regular expression '" + regex + "': " + e.what());
909 }
910 }
911
912 static const google::protobuf::Descriptor* find_descriptor(const std::string& name)
913 {
914 try
915 {
916 return dccl::DynamicProtobufManager::find_descriptor(name);
917 }
918 catch (const std::exception&)
919 {
920 return nullptr;
921 }
922 }
923
924 static bool looks_literal(const std::string& type)
925 {
926 static const std::regex literal("[A-Za-z0-9_.:]+");
927 return std::regex_match(type, literal);
928 }
929
930 void parse_textformat(const std::string& loc, const std::string& text,
931 const google::protobuf::Descriptor* desc, bool allow_partial)
932 {
933 std::unique_ptr<google::protobuf::Message> msg(dynamic_factory_.GetPrototype(desc)->New());
934 google::protobuf::TextFormat::Parser parser;
935 CollectingErrorCollector errors;
936 parser.RecordErrorsTo(&errors);
937 parser.AllowPartialMessage(allow_partial);
938 if (!parser.ParseFromString(text, msg.get()))
939 {
940 if (errors.errors.empty())
941 add(loc, "does not parse as " + desc->full_name());
942 for (const auto& e : errors.errors)
943 add(loc, "does not parse as " + desc->full_name() + ": " + e);
944 }
945 }
946
947 void parse_json(const std::string& loc, const std::string& text)
948 {
949 try
950 {
951 nlohmann::json parsed = nlohmann::json::parse(text);
952 (void)parsed;
953 }
954 catch (const std::exception& e)
955 {
956 add(loc, std::string("is not valid JSON: ") + e.what());
957 }
958 }
959
960 void check_field_path(const std::string& loc, const std::string& path,
961 const google::protobuf::Descriptor* desc)
962 {
963 static const std::regex token_regex("([^.\\[\\]]+)|\\[([0-9]+)\\]");
964 const google::protobuf::FieldDescriptor* field = nullptr;
965 bool indexed = false;
966 for (auto it = std::sregex_iterator(path.begin(), path.end(), token_regex);
967 it != std::sregex_iterator(); ++it)
968 {
969 if ((*it)[1].matched)
970 {
971 if (field && field->is_repeated() && !indexed)
972 {
973 add(loc, "'" + field->name() + "' is repeated; index it, e.g. '" +
974 field->name() + "[0]'");
975 return;
976 }
977 if (field)
978 {
979 if (field->cpp_type() != google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE)
980 {
981 add(loc, "'" + field->name() + "' is not a message");
982 return;
983 }
984 desc = field->message_type();
985 }
986 field = desc->FindFieldByName((*it)[1].str());
987 indexed = false;
988 if (!field)
989 {
990 add(loc, desc->full_name() + " has no field '" + (*it)[1].str() + "'");
991 return;
992 }
993 }
994 else
995 {
996 if (!field || !field->is_repeated() || indexed)
997 {
998 add(loc,
999 "index " + (*it)[0].str() + " applied to a field that is not repeated");
1000 return;
1001 }
1002 indexed = true;
1003 }
1004 }
1005 }
1006
1007 void check_publish(const std::string& loc, const protobuf::PubSubTestPublish& pub)
1008 {
1009 check_endpoint(loc, pub.endpoint());
1010 if (pub.repeat() < 1)
1011 add(loc + ".repeat", "must be at least 1");
1012 if (pub.interval() < 0)
1013 add(loc + ".interval", "must not be negative");
1014 if (pub.delay() < 0)
1015 add(loc + ".delay", "must not be negative");
1016
1017 int scheme = 0;
1018 std::string type;
1019 try
1020 {
1021 parse_publish_type(pub.type(), scheme, type);
1022 }
1023 catch (const std::exception&)
1024 {
1025 add(loc + ".type", "unknown marshalling scheme in '" + pub.type() + "'");
1026 return;
1027 }
1028
1029 const google::protobuf::Descriptor* desc = nullptr;
1030 switch (scheme)
1031 {
1034 {
1035 desc = find_descriptor(type);
1036 if (!desc)
1037 add(loc + ".type",
1038 "unknown type '" + type + "' (is the library that defines it loaded?)");
1039 else
1040 parse_textformat(loc + ".value", pub.value(), desc, false);
1041 break;
1042 }
1043 case MarshallingScheme::JSON: parse_json(loc + ".value", pub.value()); break;
1044 default:
1045 add(loc + ".type", "'" + pub.type() +
1046 "' does not name a supported scheme; use PROTOBUF/<type>, "
1047 "DCCL/<type>, JSON/<type> or JSON");
1048 }
1049
1050 if (is_intervehicle(pub.endpoint()))
1051 {
1053 add(loc + ".type", "intervehicle endpoints publish DCCL types only (DCCL/<type>)");
1054 check_intervehicle_group(loc, pub.group(), pub.group_field(), desc);
1055 }
1056 else
1057 {
1058 check_not_intervehicle(loc, pub.has_group_field(), pub.has_intervehicle());
1059 }
1060 }
1061
1062 bool is_intervehicle(const std::string& endpoint) const
1063 {
1064 return intervehicle_endpoints_.count(endpoint.empty() ? default_endpoint_ : endpoint);
1065 }
1066
1067 void check_intervehicle_group(const std::string& loc, const std::string& group,
1068 const std::string& group_field,
1069 const google::protobuf::Descriptor* desc)
1070 {
1071 std::uint32_t numeric;
1072 if (!detail::parse_intervehicle_group(group, numeric))
1073 {
1074 add(loc + ".group", "'" + group +
1075 "' is not a numeric group, which intervehicle "
1076 "endpoints require (e.g. \"7\")");
1077 return;
1078 }
1079 if (group_field.empty())
1080 {
1081 if (numeric != Group::broadcast_group)
1082 add(loc + ".group_field", "is required for intervehicle group " + group +
1083 " (only group 0, broadcast, needs none)");
1084 }
1085 else if (desc && !detail::group_field_descriptor(desc, group_field))
1086 {
1087 add(loc + ".group_field",
1088 "'" + group_field + "' is not a top-level integer field of " + desc->full_name());
1089 }
1090 }
1091
1092 void check_not_intervehicle(const std::string& loc, bool has_group_field, bool has_intervehicle)
1093 {
1094 if (has_group_field)
1095 add(loc + ".group_field", "applies only to intervehicle endpoints");
1096 if (has_intervehicle)
1097 add(loc + ".intervehicle", "applies only to intervehicle endpoints");
1098 }
1099
1100 void check_expect(const std::string& loc, const protobuf::PubSubTestExpect& exp)
1101 {
1102 check_endpoint(loc, exp.endpoint());
1103 check_regex(loc + ".group", exp.group());
1104
1105 std::set<int> schemes;
1106 std::string type_regex;
1107 try
1108 {
1109 detail::parse_type_spec(exp, schemes, type_regex);
1110 }
1111 catch (const std::exception&)
1112 {
1113 add(loc + ".type", "unknown marshalling scheme in '" + exp.type() + "'");
1114 return;
1115 }
1116 check_regex(loc + ".type", type_regex);
1117
1118 if (exp.has_count() && (exp.has_min_count() || exp.has_max_count()))
1119 add(loc + ".count", "'count' cannot be combined with 'min_count' or 'max_count'");
1120 if (!exp.has_count() && exp.has_max_count() && exp.max_count() < exp.min_count())
1121 add(loc + ".max_count", "is less than min_count");
1122 if (exp.has_timeout() && exp.timeout() <= 0)
1123 add(loc + ".timeout", "must be greater than zero");
1124
1125 const bool any = schemes.count(MarshallingScheme::ALL_SCHEMES);
1126 const bool protobuf_like = any || schemes.count(MarshallingScheme::PROTOBUF) ||
1127 schemes.count(MarshallingScheme::DCCL);
1128 const bool json_only =
1129 !any && schemes.size() == 1 && schemes.count(MarshallingScheme::JSON);
1130
1131 const google::protobuf::Descriptor* desc =
1132 protobuf_like ? find_descriptor(type_regex) : nullptr;
1133 if (!desc && protobuf_like && !any && looks_literal(type_regex))
1134 add(loc + ".type",
1135 "unknown type '" + type_regex + "' (is the library that defines it loaded?)");
1136
1137 if (exp.has_match())
1138 {
1139 if (desc)
1140 parse_textformat(loc + ".match", exp.match(), desc, true);
1141 else if (json_only)
1142 parse_json(loc + ".match", exp.match());
1143 }
1144
1145 if (is_intervehicle(exp.endpoint()) && detail::is_intervehicle_report(exp))
1146 {
1147 if (exp.has_group_field() || exp.has_intervehicle())
1148 add(loc, "group_field and intervehicle do not apply to acks and expiries, which "
1149 "report on this endpoint's own publications");
1150 }
1151 else if (is_intervehicle(exp.endpoint()))
1152 {
1153 if (!any && !schemes.count(MarshallingScheme::DCCL))
1154 add(loc + ".type",
1155 "intervehicle endpoints receive DCCL types only (or PROTOBUF/"
1156 "goby.middleware.intervehicle.protobuf.AckData or ExpireData for the acks and "
1157 "expiries of their own publications)");
1158 if (!desc)
1159 add(loc + ".type", "intervehicle endpoints subscribe to one type, so '" +
1160 type_regex + "' must name a loaded DCCL type");
1161 check_intervehicle_group(loc, exp.group(), exp.group_field(), desc);
1162 if (exp.intervehicle().publisher_id_size() == 0)
1163 add(loc + ".intervehicle.publisher_id",
1164 "at least one is required: a subscription is forwarded only to these modem "
1165 "ids");
1166 }
1167 else
1168 {
1169 check_not_intervehicle(loc, exp.has_group_field(), exp.has_intervehicle());
1170 }
1171
1172 for (int i = 0, n = exp.condition_size(); i < n; ++i)
1173 {
1174 const auto& cond = exp.condition(i);
1175 const std::string cloc = index(loc + ".condition", i);
1176 using Op = protobuf::PubSubTestCondition;
1177 if (cond.field().empty())
1178 add(cloc + ".field", "must not be empty");
1179 else if (desc)
1180 check_field_path(cloc + ".field", cond.field(), desc);
1181
1182 if (cond.op() == Op::REGEX)
1183 check_regex(cloc + ".value", cond.value());
1184 else if (cond.op() != Op::EXISTS && cond.op() != Op::ABSENT && !cond.has_value())
1185 add(cloc + ".value", "is required for " + Op::Op_Name(cond.op()));
1186 }
1187 }
1188
1189 void check_leaf(const std::string& loc,
1192 bool has_timeout, double timeout, double wait)
1193 {
1194 if (has_timeout && timeout <= 0)
1195 add(loc + ".timeout", "must be greater than zero");
1196 if (wait < 0)
1197 add(loc + ".wait", "must not be negative");
1198 for (int i = 0, n = pubs.size(); i < n; ++i)
1199 check_publish(index(loc + ".publish", i), pubs[i]);
1200 for (int i = 0, n = exps.size(); i < n; ++i)
1201 check_expect(index(loc + ".expect", i), exps[i]);
1202 }
1203
1204 const protobuf::PubSubTest& test_;
1205 std::set<std::string> endpoints_;
1206 std::string prefix_;
1207 std::set<std::string> intervehicle_endpoints_;
1208 std::string default_endpoint_;
1209 Issues issues_;
1210 google::protobuf::DynamicMessageFactory dynamic_factory_;
1211};
1212
1215{
1216 public:
1218
1220 std::vector<std::unique_ptr<PubSubTestEndpoint>> endpoints)
1221 : test_(test), endpoints_(std::move(endpoints))
1222 {
1223 if (endpoints_.empty())
1224 throw goby::Exception("at least one endpoint is required");
1225
1226 std::set<std::string> names, intervehicle_names;
1227 for (auto& ep : endpoints_)
1228 {
1229 if (!endpoint_index_.insert({ep->name(), ep.get()}).second)
1230 throw goby::Exception("duplicate endpoint name: " + ep->name());
1231 names.insert(ep->name());
1232 if (ep->intervehicle())
1233 intervehicle_names.insert(ep->name());
1234 }
1235 auto issues =
1236 PubSubTestValidator(test_, names)
1237 .set_intervehicle_endpoints(intervehicle_names, endpoints_.front()->name())
1238 .validate();
1239 if (!issues.empty())
1240 throw goby::Exception(issues.front().location() + ": " + issues.front().message());
1241 }
1242
1244 void set_cancel_check(std::function<bool()> cancelled) { cancelled_ = std::move(cancelled); }
1245
1247 {
1249 report.set_name(test_.name());
1250 const auto start = Clock::now();
1251
1252 try
1253 {
1254 // subscribe before ready(): a hold that requires this tool is released once its
1255 // subscriptions have reached the publishers
1256 for (auto& ep : endpoints_)
1257 ep->subscribe_all([this](const PubSubTestMessage& msg) { on_message(msg); });
1258 connect();
1259
1260 bool ok = true;
1261 for (const auto& req : test_.require_app())
1262 ok = run_require_app(req, *report.add_require_app()) && ok;
1263
1264 if (!ok)
1265 {
1266 report.set_result(protobuf::ERROR);
1267 report.set_error("required applications did not respond");
1268 }
1269 else
1270 {
1271 // after require_app: a daemon that answers health requests is ready to forward
1272 // subscriptions
1273 arm_all();
1274 run_all(report);
1275 }
1276 }
1277 catch (const std::exception& e)
1278 {
1279 report.set_result(protobuf::ERROR);
1280 report.set_error(e.what());
1281 }
1282
1283 report.set_elapsed_with_units(detail::seconds_since(start) * boost::units::si::seconds);
1284 return report;
1285 }
1286
1287 static std::string render_human(const protobuf::PubSubTestReport& report)
1288 {
1289 std::stringstream ss;
1290 ss << std::fixed << std::setprecision(2);
1291 ss << "Test: " << report.name() << " ... " << result_name(report.result()) << " ("
1292 << report.elapsed() << " s)";
1293 if (report.pass_size() > 0)
1294 {
1295 int passed = 0;
1296 for (const auto& p : report.pass()) passed += p.result() == protobuf::PASS;
1297 ss << ", " << passed << " of " << report.pass_size() << " passes passed";
1298 }
1299 ss << "\n";
1300 if (report.has_error())
1301 ss << " error: " << report.error() << "\n";
1302 for (const auto& issue : report.issue())
1303 ss << " invalid: " << issue.location() << ": " << issue.message() << "\n";
1304
1305 for (const auto& f : report.fixture())
1306 {
1307 ss << " fixture [" << f.name() << "] ... " << result_name(f.result());
1308 if (f.has_ready_time())
1309 ss << " (ready after " << f.ready_time() << " s)";
1310 if (f.has_reason())
1311 ss << ", " << f.reason();
1312 ss << "\n";
1313 if (f.has_log_file())
1314 ss << " log: " << f.log_file() << "\n";
1315 for (const auto& line : f.output_tail()) ss << " | " << line << "\n";
1316 }
1317
1318 for (const auto& req : report.require_app())
1319 {
1320 ss << " require_app [" << req.endpoint() << "] ... " << result_name(req.result())
1321 << " (" << req.elapsed() << " s" << (req.from_coroner() ? ", via goby_coroner" : "")
1322 << ")";
1323 if (!req.missing().empty())
1324 ss << " missing: " << join(req.missing());
1325 if (!req.unhealthy().empty())
1326 ss << " unhealthy: " << join(req.unhealthy());
1327 ss << "\n";
1328 }
1329
1330 for (int i = 0; i < report.run_size(); ++i)
1331 render_run(ss, report.run(i), std::to_string(i + 1));
1332
1333 // details only for passes that didn't pass
1334 for (const auto& p : report.pass())
1335 {
1336 ss << " " << p.name() << " ... " << result_name(p.result()) << " (" << p.elapsed()
1337 << " s)\n";
1338 if (p.result() == protobuf::PASS)
1339 continue;
1340 std::stringstream detail(render_human(p));
1341 std::string line;
1342 std::getline(detail, line); // the pass's own heading, already written
1343 while (std::getline(detail, line)) ss << " " << line << "\n";
1344 }
1345 return ss.str();
1346 }
1347
1348 static std::string render_json(const google::protobuf::Message& report)
1349 {
1350 std::string out;
1351 google::protobuf::util::JsonPrintOptions opts;
1352 opts.add_whitespace = true;
1353 opts.preserve_proto_field_names = true;
1354 google::protobuf::util::MessageToJsonString(report, &out, opts);
1355 return out;
1356 }
1357
1358 private:
1359 struct ExpectState
1360 {
1361 const protobuf::PubSubTestExpect* cfg;
1362 PubSubTestEndpoint* endpoint;
1363 std::set<int> schemes;
1364 std::regex type_regex;
1365 std::regex group_regex;
1366 unsigned min_count;
1367 unsigned max_count;
1368 bool has_max;
1369 bool exact; // hold until the deadline so that extra messages are seen
1370 Clock::time_point deadline;
1371 unsigned received{0};
1372 unsigned rejected{0};
1373 std::string last_rejected;
1374 bool resolved{false};
1375 bool passed{false};
1376 std::string reason;
1377 };
1378
1379 struct PublishState
1380 {
1381 const protobuf::PubSubTestPublish* cfg;
1382 PubSubTestEndpoint* endpoint;
1383 Clock::time_point next;
1384 unsigned remaining;
1385 };
1386
1388 struct Node
1389 {
1390 std::string name;
1394 double timeout;
1395 double wait{0};
1396 bool is_run{false};
1397 bool started{false};
1398 bool done{false};
1400 Clock::time_point start;
1401 double elapsed{0};
1402 std::vector<Node> children;
1403 std::size_t next_child{0};
1404 std::vector<ExpectState> expects;
1405 std::vector<PublishState> publishes;
1406 std::vector<unsigned> publish_counts;
1407 };
1408
1409 PubSubTestEndpoint* endpoint(const std::string& name)
1410 {
1411 if (name.empty())
1412 return endpoints_.front().get();
1413 auto it = endpoint_index_.find(name);
1414 if (it == endpoint_index_.end())
1415 throw goby::Exception("unknown endpoint '" + name + "'");
1416 return it->second;
1417 }
1418
1419 void arm_all()
1420 {
1421 for (const auto& run : test_.run())
1422 {
1423 for (const auto& exp : run.expect()) endpoint(exp.endpoint())->arm(exp);
1424 for (const auto& step : run.step())
1425 for (const auto& exp : step.expect()) endpoint(exp.endpoint())->arm(exp);
1426 }
1427 }
1428
1429 void poll_all()
1430 {
1431 if (cancelled_ && cancelled_())
1432 throw goby::Exception("interrupted");
1433 for (auto& ep : endpoints_) ep->poll(std::chrono::milliseconds(2));
1434 }
1435
1436 void connect()
1437 {
1438 for (auto& ep : endpoints_) ep->ready();
1439 const auto deadline = Clock::now() + detail::to_duration(test_.connect_timeout());
1440 for (;;)
1441 {
1442 bool holding = false;
1443 for (auto& ep : endpoints_) holding = holding || ep->hold_state();
1444 if (!holding)
1445 return;
1446 if (Clock::now() > deadline)
1447 throw goby::Exception("endpoints did not connect within " +
1448 std::to_string(test_.connect_timeout()) + " s");
1449 poll_all();
1450 }
1451 }
1452
1453 bool run_require_app(const protobuf::PubSubTestRequireApp& req,
1454 protobuf::PubSubTestRequireAppReport& report)
1455 {
1456 auto* ep = endpoint(req.endpoint());
1457 report.set_endpoint(ep->name());
1458 for (const auto& n : req.name()) report.add_name(n);
1459
1460 health_.clear();
1461 coroner_seen_ = false;
1462 const auto start = Clock::now();
1463 const auto deadline = start + detail::to_duration(req.timeout());
1464 const auto interval = detail::to_duration(req.request_interval());
1465 auto next_request = start;
1466
1467 auto satisfied = [&](std::vector<std::string>& missing, std::vector<std::string>& unhealthy)
1468 {
1469 missing.clear();
1470 unhealthy.clear();
1471 for (const auto& n : req.name())
1472 {
1473 auto it = health_.find(n);
1474 if (it == health_.end())
1475 missing.push_back(n);
1476 else if (req.require_ok() && it->second != protobuf::HEALTH__OK)
1477 unhealthy.push_back(n);
1478 }
1479 return missing.empty() && unhealthy.empty();
1480 };
1481
1482 std::vector<std::string> missing, unhealthy;
1483 for (;;)
1484 {
1485 if (satisfied(missing, unhealthy))
1486 break;
1487 const auto now = Clock::now();
1488 if (now > deadline)
1489 break;
1490 if (!coroner_seen_ && now >= next_request)
1491 {
1492 ep->publish_health_request();
1493 next_request = now + interval;
1494 }
1495 poll_all();
1496 }
1497
1498 const bool ok = satisfied(missing, unhealthy);
1499 report.set_result(ok ? protobuf::PASS : protobuf::ERROR);
1500 report.set_elapsed_with_units(detail::seconds_since(start) * boost::units::si::seconds);
1501 report.set_from_coroner(coroner_seen_);
1502 for (const auto& n : missing) report.add_missing(n);
1503 for (const auto& n : unhealthy) report.add_unhealthy(n);
1504 return ok;
1505 }
1506
1507 void run_all(protobuf::PubSubTestReport& report)
1508 {
1509 Node root;
1510 root.mode = test_.mode();
1511 root.publish_cfg = nullptr;
1512 root.expect_cfg = nullptr;
1513 root.timeout = test_.default_timeout();
1514 for (const auto& run : test_.run())
1515 {
1516 Node b;
1517 b.name = run.name();
1518 b.mode = run.mode();
1519 b.publish_cfg = &run.publish();
1520 b.expect_cfg = &run.expect();
1521 b.timeout = run.has_timeout() ? run.timeout() : root.timeout;
1522 b.wait = run.wait();
1523 b.is_run = true;
1524 for (const auto& step : run.step())
1525 {
1526 Node st;
1527 st.name = step.name();
1528 st.mode = protobuf::SEQUENTIAL;
1529 st.publish_cfg = &step.publish();
1530 st.expect_cfg = &step.expect();
1531 st.timeout = step.has_timeout() ? step.timeout() : b.timeout;
1532 st.wait = step.wait();
1533 b.children.push_back(std::move(st));
1534 }
1535 root.children.push_back(std::move(b));
1536 }
1537
1538 start_node(root);
1539 while (!root.done)
1540 {
1541 tick_node(root);
1542 if (!root.done)
1543 poll_all();
1544 }
1545
1546 for (const auto& b : root.children)
1547 {
1548 auto& br = *report.add_run();
1549 br.set_name(b.name);
1550 br.set_mode(b.mode);
1551 br.set_result(b.result);
1552 br.set_elapsed_with_units(b.elapsed * boost::units::si::seconds);
1553 if (b.wait > 0)
1554 br.set_wait_with_units(b.wait * boost::units::si::seconds);
1555 write_leaf_report(b, *br.mutable_publish(), *br.mutable_expect());
1556 for (const auto& st : b.children)
1557 {
1558 auto& sr = *br.add_step();
1559 sr.set_name(st.name);
1560 sr.set_result(st.result);
1561 sr.set_elapsed_with_units(st.elapsed * boost::units::si::seconds);
1562 if (st.wait > 0)
1563 sr.set_wait_with_units(st.wait * boost::units::si::seconds);
1564 write_leaf_report(st, *sr.mutable_publish(), *sr.mutable_expect());
1565 }
1566 }
1567 report.set_result(root.result);
1568 }
1569
1570 void
1571 write_leaf_report(const Node& n,
1574 {
1575 for (std::size_t i = 0; i < n.publishes.size(); ++i)
1576 {
1577 auto& pr = *pubs.Add();
1578 pr.set_endpoint(n.publishes[i].endpoint->name());
1579 pr.set_group(n.publishes[i].cfg->group());
1580 pr.set_type(n.publishes[i].cfg->type());
1581 pr.set_count(n.publish_counts[i]);
1582 }
1583 for (const auto& e : n.expects) write_expect_report(e, *exps.Add());
1584 }
1585
1586 void start_node(Node& s)
1587 {
1588 s.started = true;
1589 s.start = Clock::now();
1590
1591 if (!s.children.empty())
1592 {
1593 if (s.mode == protobuf::PARALLEL)
1594 for (auto& child : s.children) start_node(child);
1595 else
1596 start_node(s.children[s.next_child]);
1597 return;
1598 }
1599
1600 if (s.expect_cfg)
1601 {
1602 for (const auto& exp : *s.expect_cfg)
1603 {
1604 ExpectState e;
1605 e.cfg = &exp;
1606 e.endpoint = endpoint(exp.endpoint());
1607 std::string type_regex;
1608 detail::parse_type_spec(exp, e.schemes, type_regex);
1609 e.type_regex = std::regex(type_regex);
1610 e.group_regex = std::regex(exp.group());
1611 e.exact = exp.has_count();
1612 e.min_count = e.exact ? exp.count() : exp.min_count();
1613 e.has_max = e.exact || exp.has_max_count();
1614 e.max_count = e.exact ? exp.count() : exp.max_count();
1615 e.deadline =
1616 s.start + detail::to_duration(exp.has_timeout() ? exp.timeout() : s.timeout);
1617 s.expects.push_back(std::move(e));
1618 }
1619 }
1620
1621 if (s.publish_cfg)
1622 {
1623 for (const auto& pub : *s.publish_cfg)
1624 {
1625 PublishState p;
1626 p.cfg = &pub;
1627 p.endpoint = endpoint(pub.endpoint());
1628 p.next = s.start + detail::to_duration(pub.delay());
1629 p.remaining = pub.repeat();
1630 s.publishes.push_back(p);
1631 s.publish_counts.push_back(0);
1632 }
1633 }
1634 active_leaves_.insert(&s);
1635 }
1636
1637 void finish_node(Node& s, protobuf::PubSubTestResult result)
1638 {
1639 s.done = true;
1640 active_leaves_.erase(&s);
1641 s.result = result;
1642 s.elapsed = detail::seconds_since(s.start);
1643 }
1644
1645 void tick_node(Node& s)
1646 {
1647 if (s.done || !s.started)
1648 return;
1649
1650 if (!s.children.empty())
1651 {
1652 bool all_done = true, any_fail = false;
1653 for (auto& child : s.children)
1654 {
1655 if (child.started)
1656 tick_node(child);
1657 if (child.done)
1658 any_fail = any_fail || child.result != protobuf::PASS;
1659 else
1660 all_done = false;
1661 }
1662 if (s.mode == protobuf::SEQUENTIAL && s.children[s.next_child].done &&
1663 s.next_child + 1 < s.children.size())
1664 {
1665 start_node(s.children[++s.next_child]);
1666 all_done = false;
1667 }
1668 if (all_done)
1669 finish_node(s, any_fail ? protobuf::FAIL : protobuf::PASS);
1670 return;
1671 }
1672
1673 const auto now = Clock::now();
1674 bool publishing = false;
1675 for (std::size_t i = 0; i < s.publishes.size(); ++i)
1676 {
1677 auto& p = s.publishes[i];
1678 while (p.remaining > 0 && now >= p.next)
1679 {
1680 p.endpoint->publish(*p.cfg);
1681 --p.remaining;
1682 p.next += detail::to_duration(p.cfg->interval());
1683 ++s.publish_counts[i];
1684 }
1685 publishing = publishing || p.remaining > 0;
1686 }
1687
1688 bool all_resolved = true, any_fail = false;
1689 for (auto& e : s.expects)
1690 {
1691 if (!e.resolved)
1692 {
1693 const bool timed_out = now > e.deadline;
1694 if (e.has_max && e.received > e.max_count)
1695 resolve(e, false, "received more than " + std::to_string(e.max_count));
1696 else if (!e.exact && e.received >= e.min_count)
1697 resolve(e, true, "");
1698 else if (timed_out && e.received >= e.min_count)
1699 resolve(e, true, "");
1700 else if (timed_out)
1701 resolve(e, false,
1702 "received " + std::to_string(e.received) + " of " +
1703 std::to_string(e.min_count) + " before timeout");
1704 }
1705 all_resolved = all_resolved && e.resolved;
1706 any_fail = any_fail || (e.resolved && !e.passed);
1707 }
1708
1709 const bool waiting = now < s.start + detail::to_duration(s.wait);
1710 if (all_resolved && !publishing && !waiting)
1711 finish_node(s, any_fail ? protobuf::FAIL : protobuf::PASS);
1712 }
1713
1714 void resolve(ExpectState& e, bool passed, const std::string& reason)
1715 {
1716 e.resolved = true;
1717 e.passed = passed;
1718 e.reason = reason;
1719 }
1720
1721 void write_expect_report(const ExpectState& e, protobuf::PubSubTestExpectReport& r)
1722 {
1723 r.set_endpoint(e.endpoint->name());
1724 r.set_group(e.cfg->group());
1725 r.set_type(e.cfg->type());
1726 r.set_result(e.passed ? protobuf::PASS : protobuf::FAIL);
1727 r.set_received(e.received);
1728 r.set_rejected(e.rejected);
1729 r.set_min_count(e.min_count);
1730 if (e.has_max)
1731 r.set_max_count(e.max_count);
1732 if (!e.reason.empty())
1733 r.set_reason(e.reason);
1734 if (!e.last_rejected.empty())
1735 r.set_last_rejected(e.last_rejected);
1736 }
1737
1738 void on_message(const PubSubTestMessage& msg)
1739 {
1740 if (msg.scheme == MarshallingScheme::PROTOBUF)
1741 {
1742 if (msg.group == std::string(groups::health_response))
1743 {
1744 protobuf::ProcessHealth health;
1745 if (health.ParseFromArray(msg.bytes.data(), msg.bytes.size()))
1746 health_[health.name()] = health.main().state();
1747 return;
1748 }
1749 else if (msg.group == std::string(groups::health_report))
1750 {
1751 protobuf::VehicleHealth report;
1752 if (report.ParseFromArray(msg.bytes.data(), msg.bytes.size()))
1753 {
1754 coroner_seen_ = true;
1755 for (const auto& process : report.process())
1756 {
1757 // the coroner lists expected-but-dead processes too
1758 if (process.main().error() == protobuf::ERROR__PROCESS_DIED)
1759 health_.erase(process.name());
1760 else
1761 health_[process.name()] = process.main().state();
1762 }
1763 }
1764 return;
1765 }
1766 }
1767
1768 for (auto* block : active_leaves_)
1769 {
1770 for (auto& e : block->expects)
1771 {
1772 if (e.resolved || e.endpoint->name() != msg.endpoint)
1773 continue;
1774 if (!e.schemes.count(MarshallingScheme::ALL_SCHEMES) &&
1775 !e.schemes.count(msg.scheme))
1776 continue;
1777 if (!std::regex_match(msg.type, e.type_regex) ||
1778 !std::regex_match(msg.group, e.group_regex))
1779 continue;
1780
1781 std::string why;
1782 if (matches(e, msg, why))
1783 {
1784 ++e.received;
1785 }
1786 else
1787 {
1788 ++e.rejected;
1789 e.last_rejected = why;
1790 }
1791 }
1792 }
1793 }
1794
1795 bool matches(const ExpectState& e, const PubSubTestMessage& msg, std::string& why)
1796 {
1797 if (!e.cfg->has_match() && e.cfg->condition_size() == 0)
1798 return true;
1799
1800 log::LogEntry entry(msg.bytes, msg.scheme, msg.type, DynamicGroup(msg.group));
1801 nlohmann::json json;
1802 try
1803 {
1805 {
1806 auto msgs = msg.scheme == MarshallingScheme::DCCL
1807 ? dccl_plugin_.parse_message(entry)
1808 : protobuf_plugin_.parse_message(entry);
1809 if (msgs.empty())
1810 {
1811 why = "could not decode message";
1812 return false;
1813 }
1814 const auto& pb = *msgs.front();
1815
1816 if (e.cfg->has_match())
1817 {
1818 std::unique_ptr<google::protobuf::Message> expected(pb.New());
1819 google::protobuf::TextFormat::Parser parser;
1820 parser.AllowPartialMessage(true);
1821 if (!parser.ParseFromString(e.cfg->match(), expected.get()))
1822 {
1823 why = "invalid 'match' for " + pb.GetDescriptor()->full_name();
1824 return false;
1825 }
1826 if (!detail::protobuf_partial_match(*expected, pb, "", why))
1827 return false;
1828 }
1829
1830 if (e.cfg->condition_size() > 0)
1831 {
1832 std::string jstr;
1833 google::protobuf::util::JsonPrintOptions opts;
1834 opts.preserve_proto_field_names = true;
1835 google::protobuf::util::MessageToJsonString(pb, &jstr, opts);
1836 json = nlohmann::json::parse(jstr);
1837 }
1838 }
1839 else if (msg.scheme == MarshallingScheme::JSON)
1840 {
1841 json = *json_plugin_.parse_message(entry);
1842 if (e.cfg->has_match() &&
1843 !detail::json_subset(nlohmann::json::parse(e.cfg->match()), json, "", why))
1844 return false;
1845 }
1846 else
1847 {
1848 why =
1849 "cannot inspect contents of scheme " + MarshallingScheme::to_string(msg.scheme);
1850 return false;
1851 }
1852 }
1853 catch (const std::exception& ex)
1854 {
1855 why = std::string("could not decode message: ") + ex.what();
1856 return false;
1857 }
1858
1859 for (const auto& cond : e.cfg->condition())
1860 if (!detail::evaluate_condition(cond, json, why))
1861 return false;
1862 return true;
1863 }
1864
1865 static std::string result_name(protobuf::PubSubTestResult r)
1866 {
1868 }
1869
1870 static std::string join(const google::protobuf::RepeatedPtrField<std::string>& v)
1871 {
1872 std::string out;
1873 for (const auto& s : v) out += (out.empty() ? "" : ", ") + s;
1874 return out;
1875 }
1876
1877 static void
1878 render_leaf(std::stringstream& ss, const std::string& indent,
1881 {
1882 for (const auto& p : pubs)
1883 ss << indent << "publish [" << p.endpoint() << "] " << p.group() << " " << p.type()
1884 << ": sent " << p.count() << "\n";
1885 for (const auto& e : exps)
1886 {
1887 ss << indent << "expect [" << e.endpoint() << "] " << e.group() << " " << e.type()
1888 << ": " << result_name(e.result()) << ", " << e.received() << " received";
1889 if (e.rejected() > 0)
1890 ss << ", " << e.rejected() << " rejected";
1891 if (e.has_reason())
1892 ss << ", " << e.reason();
1893 if (e.has_last_rejected())
1894 ss << " (last rejected: " << e.last_rejected() << ")";
1895 ss << "\n";
1896 }
1897 }
1898
1899 static void render_run(std::stringstream& ss, const protobuf::PubSubTestRunReport& b,
1900 const std::string& index)
1901 {
1902 ss << " [" << index << "] " << b.name();
1903 if (b.step_size() > 0)
1904 ss << " (" << (b.mode() == protobuf::PARALLEL ? "parallel" : "sequential") << ")";
1905 ss << " ... " << result_name(b.result()) << " (" << b.elapsed() << " s)\n";
1906 if (b.has_wait())
1907 ss << " wait " << b.wait() << " s\n";
1908 render_leaf(ss, " ", b.publish(), b.expect());
1909 for (int i = 0; i < b.step_size(); ++i)
1910 {
1911 const auto& st = b.step(i);
1912 ss << " [" << index << "." << i + 1 << "] " << st.name() << " ... "
1913 << result_name(st.result()) << " (" << st.elapsed() << " s)\n";
1914 if (st.has_wait())
1915 ss << " wait " << st.wait() << " s\n";
1916 render_leaf(ss, " ", st.publish(), st.expect());
1917 }
1918 }
1919
1920 private:
1921 const protobuf::PubSubTest& test_;
1922 std::vector<std::unique_ptr<PubSubTestEndpoint>> endpoints_;
1923 std::map<std::string, PubSubTestEndpoint*> endpoint_index_;
1924 log::ProtobufPlugin protobuf_plugin_;
1925 log::DCCLPlugin dccl_plugin_;
1926 log::JSONPlugin json_plugin_;
1927 std::set<Node*> active_leaves_;
1928
1929 std::map<std::string, protobuf::HealthState> health_;
1930 bool coroner_seen_{false};
1931 std::function<bool()> cancelled_;
1932};
1933
1934} // namespace tool
1935} // namespace middleware
1936} // namespace goby
1937
1938#endif
simple exception class for goby applications
Definition exception.h:35
Implementation of Group for dynamic (run-time) instantiations. Use Group directly for static (compile...
Definition group.h:120
Class for grouping publications in the Goby middleware. Analogous to "topics" in ROS,...
Definition group.h:60
static constexpr std::uint32_t broadcast_group
Special group number representing the broadcast group (used when no grouping is required for a given ...
Definition group.h:63
static constexpr std::uint32_t invalid_numeric_group
Special group number representing an invalid numeric group (unsuitable for intervehicle and outer lay...
Definition group.h:65
void subscribe_dynamic(std::function< void(const Data &)> f, const Group &group=Group(), const Subscriber< Data > &subscriber=Subscriber< Data >())
Subscribe to a specific run-time defined group and data type (const reference variant)....
int poll(const std::chrono::time_point< Clock, Duration > &timeout=std::chrono::time_point< Clock, Duration >::max())
poll for data. Blocks until a data event occurs or a timeout when a particular time has been reached
Definition interface.h:375
Class that holds additional metadata and callback functions related to a publication (and is optional...
Definition publisher.h:40
Class that holds additional metadata and callback functions related to a subscription (and is optiona...
Definition subscriber.h:37
std::function< Group(const Data &)> group_func_type
Definition subscriber.h:39
static const ::PROTOBUF_NAMESPACE_ID::Descriptor * descriptor()
static const ::PROTOBUF_NAMESPACE_ID::Descriptor * descriptor()
const ::goby::acomms::protobuf::DynamicBufferConfig & buffer() const
std::shared_ptr< nlohmann::json > parse_message(LogEntry &log_entry)
std::vector< std::shared_ptr< google::protobuf::Message > > parse_message(LogEntry &log_entry)
const ::goby::middleware::intervehicle::protobuf::TransporterConfig & intervehicle() const
void set_location(ArgT0 &&arg0, ArgT... args)
void set_message(ArgT0 &&arg0, ArgT... args)
const ::goby::middleware::intervehicle::protobuf::TransporterConfig & intervehicle() const
const ::goby::middleware::protobuf::PubSubTestRequireApp & require_app(int index) const
::goby::middleware::protobuf::PubSubTestRun * mutable_run(int index)
const ::goby::middleware::protobuf::PubSubTestRun & run(int index) const
::goby::middleware::protobuf::PubSubTestRunMode mode() const
::goby::middleware::intervehicle::protobuf::TransporterConfig * mutable_intervehicle()
Type-erased connection to one layer (interprocess or intermodule) of one transport.
Definition pubsub_test.h:81
std::function< void(const PubSubTestMessage &)> MessageHandler
Definition pubsub_test.h:84
virtual const std::string & name() const =0
virtual void subscribe_all(MessageHandler handler)=0
virtual void poll(std::chrono::milliseconds wait)=0
virtual void arm(const protobuf::PubSubTestExpect &)
Called for each expectation on this endpoint once require_app has passed, before the runs start (for ...
Definition pubsub_test.h:95
virtual void publish(const protobuf::PubSubTestPublish &pub)=0
PubSubTestEndpoint on the intervehicle layer: an InterVehicleForwarder over an interprocess portal,...
void arm(const protobuf::PubSubTestExpect &exp) override
Called for each expectation on this endpoint once require_app has passed, before the runs start (for ...
PubSubTestInterVehicleEndpoint(std::string name, const PortalConfig &cfg)
void subscribe_all(MessageHandler handler) override
const std::string & name() const override
void poll(std::chrono::milliseconds wait) override
void publish(const protobuf::PubSubTestPublish &pub) override
PubSubTestEndpoint over any InterProcessPortalImplementation (interprocess or intermodule tag)
void subscribe_all(MessageHandler handler) override
void poll(std::chrono::milliseconds wait) override
void publish(const protobuf::PubSubTestPublish &pub) override
PubSubTestPortalEndpoint(std::string name, const PortalConfig &cfg, std::string tool_name)
const std::string & name() const override
Runs a PubSubTest over a set of endpoints on a single thread.
protobuf::PubSubTestReport run()
PubSubTestRunner(const protobuf::PubSubTest &test, std::vector< std::unique_ptr< PubSubTestEndpoint > > endpoints)
void set_cancel_check(std::function< bool()> cancelled)
Called regularly while running; returning true aborts the test with an error.
static std::string render_json(const google::protobuf::Message &report)
static std::string render_human(const protobuf::PubSubTestReport &report)
Checks a PubSubTest without connecting to anything: structure, endpoint references,...
PubSubTestValidator & set_intervehicle_endpoints(std::set< std::string > names, std::string default_endpoint)
Names the intervehicle endpoints, and the endpoint used when none is named, so that intervehicle rule...
std::vector< protobuf::PubSubTestIssue > Issues
PubSubTestValidator(const protobuf::PubSubTest &test, std::set< std::string > endpoint_names, std::string prefix="test")
const Reflection * GetReflection() const
Definition message.h:363
void ListFields(const Message &message, std::vector< const FieldDescriptor * > *output) const
nlohmann::json json
goby::util::logger::GroupSetter group(std::string n)
detail namespace with internal helper functions
Definition json.hpp:263
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::goby::acomms::protobuf::ModemReport, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::acomms::iridium::protobuf::Report >, 11, false > report
constexpr goby::middleware::Group health_report
Definition groups.h:38
constexpr goby::middleware::Group health_response
Definition groups.h:37
const std::string & PubSubTestResult_Name(T enum_t_value)
std::string substitute(std::string text, const std::map< std::string, std::string > &vars)
Definition systemd.h:118
void parse_publish_type(const std::string &spec, int &scheme, std::string &type)
Split a publish type specification into marshalling scheme and type name.
void unescape_variables(google::protobuf::Message &msg)
Turns each "$${" escape into a literal "${".
void find_unresolved_variables(google::protobuf::Message &msg, const std::string &prefix, std::vector< protobuf::PubSubTestIssue > &issues, const std::set< std::string > &allowed={})
Reports every ${NAME} in msg other than those in allowed (a "$${" escape is not a variable)
void expand_runs(protobuf::PubSubTest &test, std::vector< protobuf::PubSubTestIssue > &issues)
Replaces each run that has 'repeat' or 'for_each' with one plain run per pass.
void publish_tool_impl(InterprocessType &interprocess, const PublishConfig &cfg, const std::string &tool_name)
Publish a single message on the interprocess layer using the provided publish config.
constexpr int scheme()
Placeholder to provide an interface for the scheme() function family.
Definition cstr.h:65
std::string str(TimeType value=SystemClock::now< TimeType >())
Returns the provided time (or current time if omitted) as a human-readable string.
Definition convert.h:187
constexpr T e
Definition constants.h:35
The global namespace for the Goby project.
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::PROTOBUF_NAMESPACE_ID::FieldOptions, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::GobyFieldOptions >, 11, false > field
extern ::PROTOBUF_NAMESPACE_ID::internal::ExtensionIdentifier< ::PROTOBUF_NAMESPACE_ID::MessageOptions, ::PROTOBUF_NAMESPACE_ID::internal::MessageTypeTraits< ::goby::GobyMessageOptions >, 11, false > msg
int run(const goby::middleware::ConfiguratorInterface< typename App::ConfigType > &cfgtor)
Run a Goby application using the provided Configurator.
Definition interface.h:392
uint32_t index(const std::array< int8_t, 256 > &rdata, char symbol)
Definition base.h:140
type
Categories for the various JSON types used in JWTs.
Definition jwt.h:2311
STL namespace.
static int from_string(const std::string &s)
Convert from a string to a marshalling scheme id.
Definition interface.h:77
static std::string to_string(int e)
Convert a known marshalling scheme to a human-readable string or an unknown scheme to the string repr...
Definition interface.h:67
Class for parsing and serializing a given marshalling scheme. Must be specialized for a particular sc...
Definition interface.h:98
A raw message received on an endpoint.
Definition pubsub_test.h:71
std::vector< unsigned char > bytes
Definition pubsub_test.h:73