This repository was archived by the owner on Dec 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy patheverest.cpp
More file actions
1202 lines (1004 loc) · 54.5 KB
/
everest.cpp
File metadata and controls
1202 lines (1004 loc) · 54.5 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#include <cstddef>
#include <future>
#include <map>
#include <memory>
#include <set>
#include <string_view>
#include <boost/any.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <everest/logging.hpp>
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <date/date.h>
#include <date/tz.h>
#include <framework/everest.hpp>
#include <utils/conversions.hpp>
#include <utils/date.hpp>
#include <utils/error.hpp>
#include <utils/error/error_database.hpp>
#include <utils/error/error_database_map.hpp>
#include <utils/error/error_factory.hpp>
#include <utils/error/error_json.hpp>
#include <utils/error/error_manager_impl.hpp>
#include <utils/error/error_manager_req.hpp>
#include <utils/error/error_manager_req_global.hpp>
#include <utils/error/error_state_monitor.hpp>
#include <utils/error/error_type_map.hpp>
#include <utils/formatter.hpp>
namespace Everest {
using json = nlohmann::json;
using json_uri = nlohmann::json_uri;
using json_validator = nlohmann::json_schema::json_validator;
const auto remote_cmd_res_timeout_seconds = 300;
const std::array<std::string_view, 3> TELEMETRY_RESERVED_KEYS = {{"connector_id"}};
constexpr auto ensure_ready_timeout_ms = 100;
Everest::Everest(std::string module_id_, const Config& config_, bool validate_data_with_schema,
std::shared_ptr<MQTTAbstraction> mqtt_abstraction, const std::string& telemetry_prefix,
bool telemetry_enabled, bool forward_exceptions) :
mqtt_abstraction(mqtt_abstraction),
config(config_),
module_id(std::move(module_id_)),
ready_received(false),
ready_processed(false),
remote_cmd_res_timeout(remote_cmd_res_timeout_seconds),
validate_data_with_schema(validate_data_with_schema),
mqtt_everest_prefix(mqtt_abstraction->get_everest_prefix()),
mqtt_external_prefix(mqtt_abstraction->get_external_prefix()),
telemetry_prefix(telemetry_prefix),
telemetry_enabled(telemetry_enabled),
forward_exceptions(forward_exceptions) {
BOOST_LOG_FUNCTION();
this->config_service_client = std::make_shared<config::ConfigServiceClient>(mqtt_abstraction, this->module_id,
this->config.get_module_names());
EVLOG_debug << "Initializing EVerest framework...";
this->module_name = this->config.get_module_config().module_name;
this->module_manifest = this->config.get_manifests()[this->module_name];
this->module_classes = this->config.get_interfaces()[this->module_name];
this->telemetry_config = this->config.get_telemetry_config();
this->on_ready = nullptr;
// setup error_manager_req_global if enabled + error_database + error_state_monitor
if (this->module_manifest.contains("enable_global_errors") &&
this->module_manifest.at("enable_global_errors").get<bool>()) {
auto global_error_database = std::make_shared<error::ErrorDatabaseMap>();
const error::ErrorManagerReqGlobal::SubscribeGlobalAllErrorsFunc subscribe_global_all_errors_func =
[this](const error::ErrorCallback& callback, const error::ErrorCallback& clear_callback) {
this->subscribe_global_all_errors(callback, clear_callback);
};
this->global_error_manager = std::make_shared<error::ErrorManagerReqGlobal>(
std::make_shared<error::ErrorTypeMap>(this->config.get_error_map()), global_error_database,
subscribe_global_all_errors_func);
this->global_error_state_monitor = std::make_shared<error::ErrorStateMonitor>(global_error_database);
} else {
this->global_error_manager = nullptr;
this->global_error_state_monitor = nullptr;
}
this->module_tier_mappings = config.get_module_3_tier_model_mappings(this->module_id);
// setup error_managers, error_state_monitors, error_factories and error_databases for all implementations
for (const std::string& impl : Config::keys(this->module_manifest.at("provides"))) {
// setup shared database
auto error_database = std::make_shared<error::ErrorDatabaseMap>();
// setup error manager
const std::string interface_name = this->module_manifest.at("provides").at(impl).at("interface");
json interface_def = this->config.get_interface_definition(interface_name);
std::list<std::string> allowed_error_types;
for (const auto& error_namespace_it : interface_def["errors"].items()) {
for (const auto& error_name_it : error_namespace_it.value().items()) {
allowed_error_types.push_back(error_namespace_it.key() + "/" + error_name_it.key());
}
}
const error::ErrorManagerImpl::PublishErrorFunc publish_raised_error = [this, impl](const error::Error& error) {
this->publish_raised_error(impl, error);
};
const error::ErrorManagerImpl::PublishErrorFunc publish_cleared_error =
[this, impl](const error::Error& error) { this->publish_cleared_error(impl, error); };
this->impl_error_managers[impl] = std::make_shared<error::ErrorManagerImpl>(
std::make_shared<error::ErrorTypeMap>(this->config.get_error_map()), error_database, allowed_error_types,
publish_raised_error, publish_cleared_error);
// setup error state monitor
this->impl_error_state_monitors[impl] = std::make_shared<error::ErrorStateMonitor>(error_database);
std::optional<Mapping> mapping;
if (this->module_tier_mappings.has_value()) {
const auto& module_tier_mapping = this->module_tier_mappings.value();
// start with the module mapping and overwrite it (partially) with the implementation mapping
mapping = module_tier_mapping.module;
const auto impl_mapping = config.get_3_tier_model_mapping(this->module_id, impl);
if (impl_mapping.has_value()) {
if (mapping.has_value()) {
auto& mapping_value = mapping.value();
const auto& impl_mapping_value = impl_mapping.value();
if (mapping_value.evse != impl_mapping_value.evse) {
EVLOG_warning << fmt::format("Mapping value mismatch. {} ({}) evse ({}) != {} mapping evse "
"({}). Setting evse={}, please fix this in the config.",
this->module_id, this->module_name, mapping_value.evse, impl,
impl_mapping_value.evse, impl_mapping_value.evse);
mapping_value.evse = impl_mapping_value.evse;
}
if (not mapping_value.connector.has_value() and impl_mapping_value.connector.has_value()) {
mapping_value.connector = impl_mapping_value.connector;
}
if (mapping_value.connector.has_value() and impl_mapping_value.connector.has_value()) {
const auto& mapping_value_connector_value = mapping_value.connector.value();
const auto& impl_mapping_value_connector_value = impl_mapping_value.connector.value();
if (mapping_value_connector_value != impl_mapping_value_connector_value) {
EVLOG_warning
<< fmt::format("Mapping value mismatch. {} ({}) connector ({}) != {} mapping connector "
"({}). Setting connector={}, please fix this in the config.",
this->module_id, this->module_name, mapping_value_connector_value, impl,
impl_mapping_value_connector_value, impl_mapping_value_connector_value);
}
mapping_value.connector = impl_mapping_value_connector_value;
}
} else {
EVLOG_info << "No module mapping, so using impl mapping here";
mapping = impl_mapping;
}
}
}
// setup error factory
const ImplementationIdentifier default_origin(this->module_id, impl, mapping);
this->error_factories[impl] = std::make_shared<error::ErrorFactory>(
std::make_shared<error::ErrorTypeMap>(this->config.get_error_map()), default_origin);
}
// setup error_databases, error_managers and error_state_monitors for all requirements
for (const Requirement& req : config.get_requirements(module_id)) {
// setup shared database
const std::shared_ptr<error::ErrorDatabaseMap> error_database = std::make_shared<error::ErrorDatabaseMap>();
// setup error manager
// clang-format off
const auto& module_requires = this->module_manifest.at("requires");
const std::string interface_name = module_requires.at(req.id).at("interface");
// clang-format on
if (module_requires.at(req.id).contains("ignore") &&
module_requires.at(req.id).at("ignore").contains("errors") &&
module_requires.at(req.id).at("ignore").at("errors").get<bool>()) {
EVLOG_debug << "Ignoring errors for module " << req.id;
continue;
}
const json interface_def = this->config.get_interface_definition(interface_name);
std::list<std::string> allowed_error_types;
for (const auto& error_namespace_it : interface_def.at("errors").items()) {
for (const auto& error_name_it : error_namespace_it.value().items()) {
allowed_error_types.push_back(error_namespace_it.key() + "/" + error_name_it.key());
}
}
const error::ErrorManagerReq::SubscribeErrorFunc subscribe_error_func =
[this, req](const error::ErrorType& type, const error::ErrorCallback& callback,
const error::ErrorCallback& clear_callback) {
this->subscribe_error(req, type, callback, clear_callback);
};
this->req_error_managers[req] = std::make_shared<error::ErrorManagerReq>(
std::make_shared<error::ErrorTypeMap>(this->config.get_error_map()), error_database, allowed_error_types,
subscribe_error_func);
// setup error state monitor
this->req_error_state_monitors[req] = std::make_shared<error::ErrorStateMonitor>(error_database);
}
// register handler for global ready signal
const auto handle_ready_wrapper = [this](const std::string&, const json& data) { this->handle_ready(data); };
const auto everest_ready =
std::make_shared<TypedHandler>(HandlerType::GlobalReady, std::make_shared<Handler>(handle_ready_wrapper));
this->mqtt_abstraction->register_handler(fmt::format("{}ready", mqtt_everest_prefix), everest_ready, QOS::QOS2);
this->publish_metadata();
}
void Everest::spawn_main_loop_thread() {
BOOST_LOG_FUNCTION();
// TODO: since the MQTT main loop has already been started before constructing this object, this is a no-op now
this->main_loop_end = this->mqtt_abstraction->get_main_loop_future();
}
void Everest::wait_for_main_loop_end() {
BOOST_LOG_FUNCTION();
// FIXME (aw): check if mainloop has been started, simple assert for now
assert(this->main_loop_end.valid());
this->main_loop_end.get();
}
void Everest::heartbeat() {
BOOST_LOG_FUNCTION();
const auto heartbeat_topic = fmt::format("{}/heartbeat", this->config.mqtt_module_prefix(this->module_id));
using namespace date;
while (this->ready_received) {
std::ostringstream now;
now << date::utc_clock::now();
MqttMessagePayload payload{MqttMessageType::Heartbeat, json(now.str())};
this->mqtt_abstraction->publish(heartbeat_topic, payload, QOS::QOS0);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void Everest::publish_metadata() {
BOOST_LOG_FUNCTION();
const auto& module_name = this->config.get_module_name(this->module_id);
const auto& manifest = this->config.get_manifests().at(module_name);
json metadata = json({});
metadata["module"] = module_name;
if (manifest.contains("provides")) {
metadata["provides"] = json({});
for (const auto& provides : manifest.at("provides").items()) {
metadata["provides"][provides.key()] = json({});
metadata["provides"][provides.key()]["interface"] = provides.value().at("interface");
}
}
const auto metadata_topic = fmt::format("{}/metadata", this->config.mqtt_module_prefix(this->module_id));
MqttMessagePayload payload{MqttMessageType::GetConfigResponse, metadata};
this->mqtt_abstraction->publish(metadata_topic, payload, QOS::QOS2);
}
void Everest::register_on_ready_handler(const std::function<void()>& handler) {
BOOST_LOG_FUNCTION();
this->on_ready = std::make_unique<std::function<void()>>(handler);
}
std::optional<ModuleTierMappings> Everest::get_3_tier_model_mapping() {
return this->module_tier_mappings;
}
void Everest::check_code() {
BOOST_LOG_FUNCTION();
const json module_manifest = this->config.get_manifests().at(this->config.get_module_name(this->module_id));
for (const auto& element : module_manifest.at("provides").items()) {
const auto& impl_id = element.key();
const auto& impl_manifest = element.value();
const auto interface_definition = this->config.get_interface_definition(impl_manifest.at("interface"));
std::set<std::string> cmds_not_registered;
std::set<std::string> impl_manifest_cmds_set;
if (interface_definition.contains("cmds")) {
impl_manifest_cmds_set = Config::keys(interface_definition.at("cmds"));
}
const std::set<std::string> registered_cmds_set = this->registered_cmds[impl_id];
std::set_difference(impl_manifest_cmds_set.begin(), impl_manifest_cmds_set.end(), registered_cmds_set.begin(),
registered_cmds_set.end(), std::inserter(cmds_not_registered, cmds_not_registered.end()));
if (!cmds_not_registered.empty()) {
EVLOG_AND_THROW(EverestApiError(fmt::format(
"{} does not provide all cmds listed in manifest! Missing cmd(s): [{}]",
this->config.printable_identifier(module_id, impl_id), fmt::join(cmds_not_registered, " "))));
}
}
}
bool Everest::connect() {
BOOST_LOG_FUNCTION();
return this->mqtt_abstraction->connect();
}
void Everest::disconnect() {
BOOST_LOG_FUNCTION();
this->mqtt_abstraction->disconnect();
}
json Everest::call_cmd(const Requirement& req, const std::string& cmd_name, json json_args) {
BOOST_LOG_FUNCTION();
// resolve requirement
const auto& connections = this->config.resolve_requirement(this->module_id, req.id);
const auto& connection = connections.at(req.index);
// extract manifest definition of this command
const json cmd_definition = get_cmd_definition(connection.module_id, connection.implementation_id, cmd_name, true);
const json return_type = cmd_definition.at("result").at("type");
std::set<std::string> arg_names = Config::keys(json_args);
// check args against manifest
if (this->validate_data_with_schema) {
if (cmd_definition.at("arguments").size() != json_args.size()) {
EVLOG_AND_THROW(EverestApiError(
fmt::format("Call to {}->{}({}): Argument count does not match manifest!",
this->config.printable_identifier(connection.module_id, connection.implementation_id),
cmd_name, fmt::join(arg_names, ", "))));
}
std::set<std::string> unknown_arguments;
std::set<std::string> cmd_arguments;
if (cmd_definition.contains("arguments")) {
cmd_arguments = Config::keys(cmd_definition.at("arguments"));
}
std::set_difference(arg_names.begin(), arg_names.end(), cmd_arguments.begin(), cmd_arguments.end(),
std::inserter(unknown_arguments, unknown_arguments.end()));
if (!unknown_arguments.empty()) {
EVLOG_AND_THROW(EverestApiError(fmt::format(
"Call to {}->{}({}): Argument names do not match manifest: {} != {}!",
this->config.printable_identifier(connection.module_id, connection.implementation_id), cmd_name,
fmt::join(arg_names, ","), fmt::join(arg_names, ","), fmt::join(cmd_arguments, ","))));
}
}
if (this->validate_data_with_schema) {
for (const auto& arg_name : arg_names) {
try {
json_validator validator(
[this](const json_uri& uri, json& schema) { this->config.ref_loader(uri, schema); },
format_checker);
validator.set_root_schema(cmd_definition.at("arguments").at(arg_name));
validator.validate(json_args.at(arg_name));
} catch (const std::exception& e) {
EVLOG_AND_THROW(EverestApiError(fmt::format(
"Call to {}->{}({}): Argument '{}' with value '{}' could not be validated with schema: {}",
this->config.printable_identifier(connection.module_id, connection.implementation_id), cmd_name,
fmt::join(arg_names, ","), arg_name, json_args.at(arg_name).dump(2), e.what())));
}
}
}
const std::string call_id = boost::uuids::to_string(boost::uuids::random_generator()());
std::promise<CmdResult> res_promise;
std::future<CmdResult> res_future = res_promise.get_future();
const auto res_handler = [this, &res_promise, call_id, connection, cmd_name, return_type](const std::string&,
json data) {
const auto& data_id = data.at("id");
if (data_id != call_id) {
EVLOG_debug << fmt::format("RES: data_id != call_id ({} != {})", data_id, call_id);
return;
}
if (data.contains("error")) {
EVLOG_error << fmt::format(
"{}: {} during command call: {}->{}()", data.at("error").at(conversions::ERROR_TYPE).get<std::string>(),
data.at("error").at(conversions::ERROR_MSG),
this->config.printable_identifier(connection.module_id, connection.implementation_id), cmd_name);
res_promise.set_value(CmdResult{std::nullopt, data.at("error")});
} else {
EVLOG_verbose << fmt::format(
"Incoming res {} for {}->{}()", data_id,
this->config.printable_identifier(connection.module_id, connection.implementation_id), cmd_name);
res_promise.set_value(CmdResult{std::move(data["retval"]), std::nullopt});
}
};
const auto cmd_topic = fmt::format(
"{}/cmd/{}", this->config.mqtt_prefix(connection.module_id, connection.implementation_id), cmd_name);
const auto cmd_response_topic = fmt::format("{}/response/{}", cmd_topic, this->module_id);
const std::shared_ptr<TypedHandler> res_token =
std::make_shared<TypedHandler>(cmd_name, call_id, HandlerType::Result, std::make_shared<Handler>(res_handler));
this->mqtt_abstraction->register_handler(cmd_response_topic, res_token, QOS::QOS2);
const json cmd_publish_data = json::object({{"id", call_id}, {"args", json_args}, {"origin", this->module_id}});
MqttMessagePayload payload{MqttMessageType::Cmd, cmd_publish_data};
this->mqtt_abstraction->publish(cmd_topic, payload, QOS::QOS2);
// wait for result future
const std::chrono::time_point<std::chrono::steady_clock> res_wait =
std::chrono::steady_clock::now() + this->remote_cmd_res_timeout;
std::future_status res_future_status = std::future_status::deferred;
do {
res_future_status = res_future.wait_until(res_wait);
} while (res_future_status == std::future_status::deferred);
CmdResult result;
if (res_future_status == std::future_status::timeout) {
result.error = CmdResultError{
CmdErrorType::CmdTimeout,
fmt::format("Timeout while waiting for result of {}->{}()",
this->config.printable_identifier(connection.module_id, connection.implementation_id),
cmd_name)};
}
if (res_future_status == std::future_status::ready) {
result = res_future.get();
}
if (result.error.has_value()) {
const auto& error = result.error.value();
const auto error_message = fmt::format("{}", error.msg);
switch (error.event) {
case CmdErrorType::MessageParsingError:
throw MessageParsingError(error_message);
case CmdErrorType::SchemaValidationError:
throw SchemaValidationError(error_message);
case CmdErrorType::HandlerException:
throw HandlerException(error_message);
case CmdErrorType::CmdTimeout:
throw CmdTimeout(error_message);
case CmdErrorType::Shutdown:
throw Shutdown(error_message);
case CmdErrorType::NotReady:
throw NotReady(error_message);
default:
throw CmdError(fmt::format("{}: {}", conversions::cmd_error_type_to_string(error.event), error.msg));
}
}
if (not result.result.has_value()) {
throw CmdError("Command did not return result");
}
return result.result.value();
}
void Everest::publish_var(const std::string& impl_id, const std::string& var_name, json value) {
BOOST_LOG_FUNCTION();
// check arguments
if (this->validate_data_with_schema) {
const auto impl_intf = this->config.get_interface_definitions().at(this->module_classes.at(impl_id));
if (!module_manifest.at("provides").contains(impl_id)) {
EVLOG_AND_THROW(EverestApiError(
fmt::format("Implementation '{}' not declared in manifest of module '{}'!", impl_id, this->module_id)));
}
if (!impl_intf.at("vars").contains(var_name)) {
EVLOG_AND_THROW(
EverestApiError(fmt::format("{} does not declare var '{}' in manifest!",
this->config.printable_identifier(this->module_id, impl_id), var_name)));
}
// validate var contents before publishing
const auto var_definition = impl_intf.at("vars").at(var_name);
try {
json_validator validator(
[this](const json_uri& uri, json& schema) { this->config.ref_loader(uri, schema); }, format_checker);
validator.set_root_schema(var_definition);
validator.validate(value);
} catch (const std::exception& e) {
EVLOG_AND_THROW(EverestApiError(fmt::format(
"Publish var of {} with variable name '{}' with value: {}\ncould not be validated with schema: {}",
this->config.printable_identifier(this->module_id, impl_id), var_name, value.dump(2), e.what())));
}
}
const auto var_topic = fmt::format("{}/var/{}", this->config.mqtt_prefix(this->module_id, impl_id), var_name);
MqttMessagePayload payload{MqttMessageType::Var, value};
// FIXME(kai): implement an efficient way of choosing qos for each variable
this->mqtt_abstraction->publish(var_topic, payload, QOS::QOS2);
}
void Everest::subscribe_var(const Requirement& req, const std::string& var_name, const JsonCallback& callback) {
BOOST_LOG_FUNCTION();
EVLOG_debug << fmt::format("subscribing to var: {}:{}", req.id, var_name);
// resolve requirement
const auto& connections = this->config.resolve_requirement(this->module_id, req.id);
const auto& connection = connections.at(req.index);
const auto requirement_module_id = connection.module_id;
const auto module_name = this->config.get_module_name(requirement_module_id);
const auto requirement_impl_id = connection.implementation_id;
const auto requirement_impl_manifest = this->config.get_interface_definitions().at(
this->config.get_interfaces().at(module_name).at(requirement_impl_id));
if (!requirement_impl_manifest.at("vars").contains(var_name)) {
EVLOG_AND_THROW(EverestApiError(
fmt::format("{}->{}: Variable not defined in manifest!",
this->config.printable_identifier(requirement_module_id, requirement_impl_id), var_name)));
}
const auto requirement_manifest_vardef = requirement_impl_manifest.at("vars").at(var_name);
const auto handler = [this, requirement_module_id, requirement_impl_id, requirement_manifest_vardef, var_name,
callback](const std::string&, json const& data) {
EVLOG_verbose << fmt::format(
"Incoming {}->{}", this->config.printable_identifier(requirement_module_id, requirement_impl_id), var_name);
if (this->validate_data_with_schema) {
// check data and ignore it if not matching (publishing it should have been prohibited already)
try {
json_validator validator(
[this](const json_uri& uri, json& schema) { this->config.ref_loader(uri, schema); },
format_checker);
validator.set_root_schema(requirement_manifest_vardef);
validator.validate(data);
} catch (const std::exception& e) {
EVLOG_warning << fmt::format("Ignoring incoming var '{}' because not matching manifest schema: {}",
var_name, e.what());
return;
}
}
callback(data);
};
const auto var_topic =
fmt::format("{}/var/{}", this->config.mqtt_prefix(requirement_module_id, requirement_impl_id), var_name);
// TODO(kai): multiple subscription should be perfectly fine here!
const std::shared_ptr<TypedHandler> token =
std::make_shared<TypedHandler>(var_name, HandlerType::SubscribeVar, std::make_shared<Handler>(handler));
this->mqtt_abstraction->register_handler(var_topic, token, QOS::QOS2);
}
void Everest::subscribe_error(const Requirement& req, const error::ErrorType& error_type,
const error::ErrorCallback& raise_callback, const error::ErrorCallback& clear_callback) {
BOOST_LOG_FUNCTION();
EVLOG_debug << fmt::format("subscribing to error: {}:{}", req.id, error_type);
// resolve requirement
const auto& connections = this->config.resolve_requirement(this->module_id, req.id);
const auto& connection = connections.at(req.index);
const std::string requirement_module_id = connection.module_id;
const std::string module_name = this->config.get_module_name(requirement_module_id);
const std::string requirement_impl_id = connection.implementation_id;
const json requirement_impl_if = this->config.get_interface_definitions().at(
this->config.get_interfaces().at(module_name).at(requirement_impl_id));
// check if requirement is allowed to publish this error_type
// split error_type at '/'
const std::size_t pos = error_type.find('/');
if (pos == std::string::npos) {
EVLOG_error << fmt::format("Error type {} is not valid, ignore subscription", error_type);
return;
}
const std::string error_type_namespace = error_type.substr(0, pos);
const std::string error_type_name = error_type.substr(pos + 1);
if (!requirement_impl_if.contains("errors") || !requirement_impl_if.at("errors").contains(error_type_namespace) ||
!requirement_impl_if.at("errors").at(error_type_namespace).contains(error_type_name)) {
EVLOG_error << fmt::format("{}: Error {} not listed in interface, ignore subscription!",
this->config.printable_identifier(requirement_module_id, requirement_impl_id),
error_type);
return;
}
const auto error_handler = [this, requirement_module_id, requirement_impl_id, error_type, raise_callback,
clear_callback](const std::string&, json const& data) {
auto error = data.get<error::Error>();
if (error.type != error_type) {
// error type doesn't match, ignoring
return;
}
switch (error.state) {
case error::State::Active:
EVLOG_debug << fmt::format("Incoming error {}->{}",
this->config.printable_identifier(requirement_module_id, requirement_impl_id),
error_type);
raise_callback(error);
break;
case error::State::ClearedByModule:
case error::State::ClearedByReboot:
EVLOG_debug << fmt::format("Error cleared {}->{}",
this->config.printable_identifier(requirement_module_id, requirement_impl_id),
error_type);
clear_callback(error);
break;
}
};
const std::string error_topic =
fmt::format("{}/error/{}", this->config.mqtt_prefix(requirement_module_id, requirement_impl_id), error_type);
const std::shared_ptr<TypedHandler> error_token = std::make_shared<TypedHandler>(
error_type, HandlerType::SubscribeError, std::make_shared<Handler>(error_handler));
this->mqtt_abstraction->register_handler(error_topic, error_token, QOS::QOS2);
}
std::shared_ptr<error::ErrorManagerImpl> Everest::get_error_manager_impl(const std::string& impl_id) {
if (this->impl_error_managers.find(impl_id) == this->impl_error_managers.end()) {
EVLOG_error << fmt::format("Error manager for {} not found!", impl_id);
return nullptr;
}
return this->impl_error_managers.at(impl_id);
}
std::shared_ptr<error::ErrorStateMonitor> Everest::get_error_state_monitor_impl(const std::string& impl_id) {
if (this->impl_error_state_monitors.find(impl_id) == this->impl_error_state_monitors.end()) {
EVLOG_error << fmt::format("Error state monitor for {} not found!", impl_id);
return nullptr;
}
return this->impl_error_state_monitors.at(impl_id);
}
std::shared_ptr<error::ErrorFactory> Everest::get_error_factory(const std::string& impl_id) {
if (this->error_factories.find(impl_id) == this->error_factories.end()) {
EVLOG_error << fmt::format("Error factory for {} not found!", impl_id);
return nullptr;
}
return this->error_factories.at(impl_id);
}
std::shared_ptr<error::ErrorManagerReq> Everest::get_error_manager_req(const Requirement& req) {
if (this->req_error_managers.find(req) == this->req_error_managers.end()) {
throw std::runtime_error(fmt::format("Error manager for {} not found", req.id));
}
return this->req_error_managers.at(req);
}
std::shared_ptr<error::ErrorStateMonitor> Everest::get_error_state_monitor_req(const Requirement& req) {
if (this->req_error_state_monitors.find(req) == this->req_error_state_monitors.end()) {
EVLOG_error << fmt::format("Error state monitor for {} not found!", req.id);
return nullptr;
}
return this->req_error_state_monitors.at(req);
}
std::shared_ptr<error::ErrorManagerReqGlobal> Everest::get_global_error_manager() const {
if (this->global_error_manager == nullptr) {
EVLOG_warning << "This module has no global_error_manager, returning nullptr";
}
return this->global_error_manager;
}
std::shared_ptr<error::ErrorStateMonitor> Everest::get_global_error_state_monitor() const {
if (this->global_error_state_monitor == nullptr) {
EVLOG_warning << "This module has no global_error_state_monitor, returning nullptr";
}
return this->global_error_state_monitor;
}
std::shared_ptr<config::ConfigServiceClient> Everest::get_config_service_client() const {
return this->config_service_client;
}
void Everest::subscribe_global_all_errors(const error::ErrorCallback& raise_callback,
const error::ErrorCallback& clear_callback) {
BOOST_LOG_FUNCTION();
EVLOG_debug << fmt::format("subscribing to all errors");
if (not this->config.get_module_info(this->module_id).global_errors_enabled) {
EVLOG_error << fmt::format("Module {} is not allowed to subscribe to all errors, ignore subscription",
this->config.printable_identifier(this->module_id));
return;
}
const auto error_handler = [this, raise_callback, clear_callback](const std::string&, json const& data) {
error::Error error = data.get<error::Error>();
switch (error.state) {
case error::State::Active:
EVLOG_debug << fmt::format(
"Incoming error {}->{}",
this->config.printable_identifier(error.origin.module_id, error.origin.implementation_id), error.type);
raise_callback(error);
break;
case error::State::ClearedByModule:
case error::State::ClearedByReboot:
EVLOG_debug << fmt::format(
"Incoming error cleared {}->{}",
this->config.printable_identifier(error.origin.module_id, error.origin.implementation_id), error.type);
clear_callback(error);
break;
}
};
for (const auto& [module_id, module_name] : this->config.get_module_names()) {
const json provides = this->config.get_manifests().at(module_name).at("provides");
for (const auto& impl : provides.items()) {
const std::string& impl_id = impl.key();
const std::string error_topic = fmt::format("{}/error/#", this->config.mqtt_prefix(module_id, impl_id));
const std::shared_ptr<TypedHandler> error_token =
std::make_shared<TypedHandler>(HandlerType::SubscribeError, std::make_shared<Handler>(error_handler));
this->mqtt_abstraction->register_handler(error_topic, error_token, QOS::QOS2);
}
}
}
void Everest::publish_raised_error(const std::string& impl_id, const error::Error& error) {
BOOST_LOG_FUNCTION();
const auto error_topic = fmt::format("{}/error/{}", this->config.mqtt_prefix(this->module_id, impl_id), error.type);
MqttMessagePayload payload{MqttMessageType::RaiseError, json(error)};
this->mqtt_abstraction->publish(error_topic, payload, QOS::QOS2);
}
void Everest::publish_cleared_error(const std::string& impl_id, const error::Error& error) {
BOOST_LOG_FUNCTION();
const auto error_topic = fmt::format("{}/error/{}", this->config.mqtt_prefix(this->module_id, impl_id), error.type);
MqttMessagePayload payload{MqttMessageType::ClearError, json(error)};
this->mqtt_abstraction->publish(error_topic, payload, QOS::QOS2);
}
void Everest::external_mqtt_publish(const std::string& topic, const std::string& data) {
BOOST_LOG_FUNCTION();
check_external_mqtt();
this->mqtt_abstraction->publish(fmt::format("{}{}", this->mqtt_external_prefix, topic), data);
}
UnsubscribeToken Everest::provide_external_mqtt_handler(const std::string& topic, const StringHandler& handler) {
BOOST_LOG_FUNCTION();
const auto external_topic = check_external_mqtt(topic);
return create_external_handler(
topic, external_topic, [handler, external_topic](const std::string&, json const& data) {
EVLOG_verbose << fmt::format("Incoming external mqtt data for topic '{}'...", external_topic);
if (!data.is_string()) {
EVLOG_AND_THROW(
EverestInternalError("External mqtt result is not a string (that should never happen)"));
}
handler(data.get<std::string>());
});
}
UnsubscribeToken Everest::provide_external_mqtt_handler(const std::string& topic, const StringPairHandler& handler) {
BOOST_LOG_FUNCTION();
const auto external_topic = check_external_mqtt(topic);
return create_external_handler(topic, external_topic, [handler](const std::string& topic, const json& data) {
EVLOG_verbose << fmt::format("Incoming external mqtt data for topic '{}'...", topic);
const std::string data_s = (data.is_string()) ? std::string(data) : data.dump();
handler(topic, data_s);
});
}
void Everest::telemetry_publish(const std::string& topic, const std::string& data) {
BOOST_LOG_FUNCTION();
MqttMessagePayload payload{MqttMessageType::ExternalMQTT, data};
this->mqtt_abstraction->publish(fmt::format("{}{}", this->telemetry_prefix, topic), payload);
}
void Everest::telemetry_publish(const std::string& category, const std::string& subcategory, const std::string& type,
const TelemetryMap& telemetry) {
BOOST_LOG_FUNCTION();
if (!this->telemetry_enabled || !this->telemetry_config.has_value()) {
// telemetry not enabled for this module instance in config
return;
}
const int id = telemetry_config->id;
const std::string id_string = std::to_string(id);
auto telemetry_data =
json::object({{"timestamp", Date::to_rfc3339(date::utc_clock::now())}, {"connector_id", id}, {"type", type}});
for (auto&& [key, entry] : telemetry) {
if (std::any_of(TELEMETRY_RESERVED_KEYS.begin(), TELEMETRY_RESERVED_KEYS.end(),
[&key_ = key](const auto& element) { return element == key_; })) {
EVLOG_warning << "Telemetry key " << key << " is reserved and will be overwritten.";
} else {
json data;
std::visit([&data](auto& value) { data = value; }, entry);
telemetry_data[key] = data;
}
}
const std::string topic = category + "/" + id_string + "/" + subcategory;
this->telemetry_publish(topic, telemetry_data.dump());
}
void Everest::signal_ready() {
BOOST_LOG_FUNCTION();
const auto ready_topic = fmt::format("{}/ready", this->config.mqtt_module_prefix(this->module_id));
MqttMessagePayload payload{MqttMessageType::ModuleReady, json(true)};
this->mqtt_abstraction->publish(ready_topic, payload, QOS::QOS2);
}
void Everest::ensure_ready() const {
/// When calling this we actually expect that `ready_processed` is true.
while (!ready_processed) { // In C++20 we might mark it as [[unlikely]]
EVLOG_warning << "Module has not processed `ready` yet.";
std::this_thread::sleep_for(std::chrono::milliseconds(ensure_ready_timeout_ms));
}
}
///
/// \brief Ready handler for global readyness (e.g. all modules are ready now).
/// This will called when receiving the global ready signal from manager.
///
void Everest::handle_ready(const json& data) {
BOOST_LOG_FUNCTION();
EVLOG_debug << fmt::format("handle_ready: {}", data.dump());
bool ready = false;
if (data.is_boolean()) {
ready = data.get<bool>();
}
// ignore non-truish ready signals
if (!ready) {
return;
}
if (this->ready_received) {
EVLOG_warning << "Ignoring repeated everest ready signal (possibly triggered by "
"restarting a standalone module)!";
return;
}
this->ready_received = true;
// call module ready handler
EVLOG_debug << "Framework now ready to process events, calling module ready handler";
if (this->on_ready != nullptr) {
const auto on_ready_handler = *on_ready;
on_ready_handler();
}
this->ready_processed = true;
// TODO(kai): make heartbeat interval configurable, disable it completely until then
// this->heartbeat_thread = std::thread(&Everest::heartbeat, this);
}
void Everest::provide_cmd(const std::string& impl_id, const std::string& cmd_name, const JsonCommand& handler) {
BOOST_LOG_FUNCTION();
// extract manifest definition of this command
const json cmd_definition = get_cmd_definition(this->module_id, impl_id, cmd_name, false);
if (this->registered_cmds.count(impl_id) != 0 && this->registered_cmds.at(impl_id).count(cmd_name) != 0) {
EVLOG_AND_THROW(EverestApiError(fmt::format(
"{}->{}(...): Handler for this cmd already registered (you can not register a cmd handler twice)!",
this->config.printable_identifier(this->module_id, impl_id), cmd_name)));
}
const auto cmd_topic = fmt::format("{}/cmd/{}", this->config.mqtt_prefix(this->module_id, impl_id), cmd_name);
// define command wrapper
const auto wrapper = [this, cmd_topic, impl_id, cmd_name, handler, cmd_definition](const std::string&, json data) {
BOOST_LOG_FUNCTION();
std::set<std::string> arg_names;
if (cmd_definition.contains("arguments")) {
arg_names = Config::keys(cmd_definition.at("arguments"));
}
EVLOG_verbose << fmt::format("Incoming {}->{}({}) for <handler>",
this->config.printable_identifier(this->module_id, impl_id), cmd_name,
fmt::join(arg_names, ","));
json res_data = json({});
try {
res_data["id"] = data.at("id");
} catch (const json::exception& e) {
throw CmdError("Command did not contain id");
}
std::optional<CmdResultError> error;
// check data and ignore it if not matching (publishing it should have
// been prohibited already)
if (this->validate_data_with_schema) {
try {
for (const auto& arg_name : arg_names) {
if (!data.at("args").contains(arg_name)) {
EVLOG_AND_THROW(std::invalid_argument(
fmt::format("Missing argument {} for {}!", arg_name,
this->config.printable_identifier(this->module_id, impl_id))));
}
json_validator validator(
[this](const json_uri& uri, json& schema) { this->config.ref_loader(uri, schema); },
format_checker);
validator.set_root_schema(cmd_definition.at("arguments").at(arg_name));
validator.validate(data.at("args").at(arg_name));
}
} catch (const std::exception& e) {
EVLOG_warning << fmt::format("Ignoring incoming cmd '{}' because not matching manifest schema: {}",
cmd_name, e.what());
error = CmdResultError{CmdErrorType::SchemaValidationError, e.what()};
}
}
// publish results
// call real cmd handler
try {
if (not error.has_value()) {
res_data["retval"] = handler(data.at("args"));
}
} catch (const MessageParsingError& e) {
error = CmdResultError{CmdErrorType::MessageParsingError, e.what(), std::current_exception()};
} catch (const SchemaValidationError& e) {
error = CmdResultError{CmdErrorType::SchemaValidationError, e.what(), std::current_exception()};
} catch (const CmdTimeout& e) {
error = CmdResultError{CmdErrorType::CmdTimeout, e.what(), std::current_exception()};
} catch (const Shutdown& e) {
error = CmdResultError{CmdErrorType::Shutdown, e.what(), std::current_exception()};
} catch (const NotReady& e) {
error = CmdResultError{CmdErrorType::NotReady, e.what(), std::current_exception()};
} catch (const std::exception& e) {
EVLOG_error << fmt::format("Exception during handling of: {}->{}({}): {}",
this->config.printable_identifier(this->module_id, impl_id), cmd_name,
fmt::join(arg_names, ","), e.what());
error = CmdResultError{CmdErrorType::HandlerException, e.what(), std::current_exception()};
} catch (...) {
EVLOG_error << fmt::format("Unknown exception during handling of: {}->{}({})",
this->config.printable_identifier(this->module_id, impl_id), cmd_name,
fmt::join(arg_names, ","));
error = CmdResultError{CmdErrorType::HandlerException, "Unknown exception", std::current_exception()};
}
// check retval against manifest
if (not error.has_value() && this->validate_data_with_schema) {
try {
// only use validator on non-null return types
if (!(res_data.at("retval").is_null() &&
(!cmd_definition.contains("result") || cmd_definition.at("result").is_null()))) {
json_validator validator(
[this](const json_uri& uri, json& schema) { this->config.ref_loader(uri, schema); },
format_checker);
validator.set_root_schema(cmd_definition.at("result"));
validator.validate(res_data.at("retval"));
}
} catch (const std::exception& e) {
EVLOG_warning << fmt::format("Ignoring return value of cmd '{}' because the validation of the result "
"failed: {}\ndefinition: {}\ndata: {}",
cmd_name, e.what(), cmd_definition, res_data);
error = CmdResultError{CmdErrorType::SchemaValidationError, e.what()};
}
}
res_data["origin"] = this->module_id;
if (error.has_value()) {
res_data["error"] = error.value();
}
MqttMessagePayload payload{MqttMessageType::CmdResult, res_data};
const auto final_cmd_response_topic =
fmt::format("{}/response/{}", cmd_topic, data.at("origin").get<std::string>());
this->mqtt_abstraction->publish(final_cmd_response_topic, payload);
// re-throw exception caught in handler
if (error.has_value()) {
auto err = error.value();
if (err.event == CmdErrorType::HandlerException and not this->forward_exceptions) {
if (err.ex) {
std::rethrow_exception(err.ex);
} else {
throw std::runtime_error("Unknown exception during cmd handling");
}
}
}
};
const auto typed_handler =
std::make_shared<TypedHandler>(cmd_name, HandlerType::Call, std::make_shared<Handler>(wrapper));
this->mqtt_abstraction->register_handler(cmd_topic, typed_handler, QOS::QOS2);
// this list of registered cmds will be used later on to check if all cmds