helics 3.7.0
Loading...
Searching...
No Matches
BrokerBase.hpp
Go to the documentation of this file.
1/*
2Copyright (c) 2017-2026,
3Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Energy
4Innovation LLC. See the top-level NOTICE for additional details. All rights reserved.
5SPDX-License-Identifier: BSD-3-Clause
6*/
7#pragma once
14#include "ActionMessage.hpp"
15#include "FederateIdExtra.hpp"
16#include "gmlc/containers/BlockingPriorityQueue.hpp"
17
18#include <atomic>
19#include <limits>
20#include <memory>
21#include <nlohmann/json_fwd.hpp>
22#include <string>
23#include <thread>
24#include <utility>
25#include <vector>
26
27namespace spdlog {
28class logger;
29}
30
31namespace helics {
32class BaseTimeCoordinator;
33class helicsCLI11App;
34class ProfilerBuffer;
35class LogBuffer;
36class LogManager;
40 protected:
41 static constexpr double mInvalidSimulationTime{-98763.2};
43 std::atomic<GlobalBrokerId> global_id{parent_broker_id};
49
51 int32_t minFederateCount{1};
53 int32_t minBrokerCount{0};
54 int32_t maxFederateCount{(std::numeric_limits<int32_t>::max)()};
55 int32_t maxBrokerCount{(std::numeric_limits<int32_t>::max)()};
57 int32_t minChildCount{0};
63 std::vector<std::string> requiredFederates;
64 int32_t maxIterationCount{10000};
66 Time timeout{30.0};
73 std::string identifier;
74 std::string brokerKey;
76 // address is mutable since during initial phases it may not be fixed so to maintain a
77 // consistent public interface for extracting it this variable may need to be updated in a
78 // constant function
79 mutable std::string address;
80
83 std::atomic<bool> haltOperations{false};
87 bool terminate_on_error{false};
89 bool debugging{false};
91 bool observer{false};
93 bool globalTime{false};
95 bool asyncTime{false};
97 bool dynamicFederation{false};
100
101 private:
103 std::atomic<bool> mainLoopIsRunning{false};
105 bool dumplog{false};
108 bool queueDisabled{false};
110 bool disable_timer{false};
112 std::atomic<std::size_t> messageCounter{0};
113
114 protected:
115 std::unique_ptr<BaseTimeCoordinator> timeCoord;
116 gmlc::containers::BlockingPriorityQueue<ActionMessage> actionQueue;
117 std::shared_ptr<LogManager> mLogManager;
119 enum class BrokerState : int16_t {
120 CREATED = -10,
121 CONFIGURING = -7,
122 CONFIGURED = -6,
123 CONNECTING = -4,
124 CONNECTED = -3,
125 INITIALIZING = -1,
126 OPERATING = 0,
127 CONNECTED_ERROR = 3,
128 TERMINATING = 4,
130 TERMINATED = 6,
131 ERRORED = 7,
132 };
133
134 enum class TickForwardingReasons : uint32_t {
135 NONE = 0,
136 NO_COMMS = 0x01,
137 PING_RESPONSE = 0x02,
138 QUERY_TIMEOUT = 0x04,
139 GRANT_TIMEOUT = 0x08,
140 DISCONNECT_TIMEOUT = 0x10
141 };
142 bool noAutomaticID{false};
143 bool hasTimeDependency{false};
147 bool hasFilters{false};
148
149 bool no_ping{false};
150 bool uuid_like{false};
153 bool enable_profiling{false};
157 bool globalDisconnect{false};
160 decltype(std::chrono::steady_clock::now()) errorTimeStart;
162 decltype(std::chrono::steady_clock::now()) disconnectTime;
163 std::atomic<int> lastErrorCode{0};
164 std::string lastErrorString;
165 std::string configString;
166 bool fileInUse{false};
167
168 private:
170 std::shared_ptr<ProfilerBuffer> prBuff;
171
173 bool forwardTick{false};
175 uint32_t forwardingReasons{0U};
177 std::atomic<BrokerState> brokerState{BrokerState::CREATED};
178
179 public:
180 explicit BrokerBase(bool DisableQueue = false) noexcept;
181 explicit BrokerBase(std::string_view broker_name, bool DisableQueue = false);
182
183 virtual ~BrokerBase();
184
188 void loadInfoFromToml(const std::string& toml, bool runArgParser = true);
189
193 void loadInfoFromJson(const std::string& json, bool runArgParser = true);
194
198 int parseArgs(int argc, char* argv[]);
202 int parseArgs(std::vector<std::string> args);
206 int parseArgs(std::string_view initializationString);
209 virtual void configureBase();
210
212 void addActionMessage(const ActionMessage& message);
214 void addActionMessage(ActionMessage&& message);
215
222 std::function<void(int level, std::string_view identifier, std::string_view message)>
223 logFunction);
225 void logFlush();
227 bool isRunning() const { return mainLoopIsRunning.load(); }
229 void setLogLevel(int32_t level);
234 void setLogLevels(int32_t consoleLevel, int32_t fileLevel);
236 GlobalBrokerId getGlobalId() const { return global_id.load(); }
237
238 private:
240 void queueProcessingLoop();
243 action_message_def::action_t commandProcessor(ActionMessage& command);
244
246 std::shared_ptr<helicsCLI11App> generateBaseCLI();
248 void baseConfigure(ActionMessage& command);
249
252 void addActionMessage(ActionMessage&& message) const;
253
254 protected:
256 static bool isReasonForTick(std::uint32_t code, TickForwardingReasons reason)
257 {
258 return ((static_cast<std::uint32_t>(reason) & code) != 0);
259 }
261 void setTickForwarding(TickForwardingReasons reason, bool value = true);
262 BrokerState getBrokerState() const { return brokerState.load(); }
263 bool setBrokerState(BrokerState newState);
264 bool transitionBrokerState(BrokerState expectedState, BrokerState newState);
266 virtual void processDisconnect(bool skipUnregister = false) = 0;
269 virtual bool tryReconnect() = 0;
272 virtual void processCommand(ActionMessage&& cmd) = 0;
278 virtual void processPriorityCommand(ActionMessage&& command) = 0;
279
284 bool sendToLogger(GlobalFederateId federateID,
285 int logLevel,
286 std::string_view name,
287 std::string_view message,
288 bool fromRemote = false) const;
290 void saveProfilingData(std::string_view message);
292 void writeProfilingData();
296 virtual std::string generateLocalAddressString() const = 0;
298 virtual std::shared_ptr<helicsCLI11App> generateCLI();
300 void setErrorState(int eCode, std::string_view estring);
302 void setLoggingFile(std::string_view lfile);
304 bool getFlagValue(int32_t flag) const;
306 virtual double getSimulationTime() const { return mInvalidSimulationTime; }
308 std::pair<bool, std::vector<std::string_view>> processBaseCommands(ActionMessage& command);
310 void addBaseInformation(nlohmann::json& base, bool hasParent) const;
311
312 public:
314 std::function<void(int, std::string_view, std::string_view)> getLoggingCallback() const;
316 void joinAllThreads();
318 std::size_t currentMessageCounter() const
319 {
320 return messageCounter.load(std::memory_order_acquire);
321 }
322 friend class TimeoutMonitor;
323 friend const std::string& brokerStateName(BrokerState state);
324};
325
328const std::string& brokerStateName(BrokerBase::BrokerState state);
329
330} // namespace helics
Definition ActionMessage.hpp:30
Definition BrokerBase.hpp:39
std::thread queueProcessingThread
Definition BrokerBase.hpp:81
void setLoggingFile(std::string_view lfile)
Definition BrokerBase.cpp:645
decltype(std::chrono::steady_clock::now()) disconnectTime
time when the disconnect started
Definition BrokerBase.hpp:162
friend const std::string & brokerStateName(BrokerState state)
Definition BrokerBase.cpp:1191
bool debugging
flag indicating operation in a user debugging mode
Definition BrokerBase.hpp:89
void setLogLevels(int32_t consoleLevel, int32_t fileLevel)
Definition BrokerBase.cpp:771
std::string configString
storage for a config file location
Definition BrokerBase.hpp:165
void setLoggerFunction(std::function< void(int level, std::string_view identifier, std::string_view message)> logFunction)
Definition BrokerBase.cpp:752
virtual void configureBase()
Definition BrokerBase.cpp:515
int32_t minLocalBrokerCount
Definition BrokerBase.hpp:61
bool observer
flag indicating that the broker is an observer only
Definition BrokerBase.hpp:91
int32_t minFederateCount
Definition BrokerBase.hpp:51
std::string identifier
an identifier for the broker
Definition BrokerBase.hpp:73
void joinAllThreads()
Definition BrokerBase.cpp:97
std::atomic< int > lastErrorCode
storage for last error code
Definition BrokerBase.hpp:163
static bool isReasonForTick(std::uint32_t code, TickForwardingReasons reason)
Definition BrokerBase.hpp:256
bool no_ping
indicator that the broker is not very responsive to ping requests
Definition BrokerBase.hpp:149
GlobalBrokerId higher_broker_id
the id code of the broker 1 level about this broker
Definition BrokerBase.hpp:46
BrokerState
Definition BrokerBase.hpp:119
@ CONFIGURED
the broker itself has been configured and is ready to connect
@ TERMINATING_ERROR
the termination process has started while in an error state
@ OPERATING
normal operating conditions
@ CONNECTED_ERROR
error state but still connected
@ INITIALIZING
the enter initialization process has started
@ CREATED
the broker has been created
@ CONNECTING
the connection process has started
@ TERMINATED
the termination process has started
@ CONNECTED
the connection process has completed
@ CONFIGURING
the broker is in the processing of configuring
@ TERMINATING
the termination process has started
@ ERRORED
an error was encountered
Time timeout
timeout to wait to establish a broker connection before giving up
Definition BrokerBase.hpp:66
void setTickForwarding(TickForwardingReasons reason, bool value=true)
Definition BrokerBase.cpp:1084
void saveProfilingData(std::string_view message)
Definition BrokerBase.cpp:596
std::string brokerKey
Definition BrokerBase.hpp:74
bool isRunning() const
Definition BrokerBase.hpp:227
bool sendToLogger(GlobalFederateId federateID, int logLevel, std::string_view name, std::string_view message, bool fromRemote=false) const
Definition BrokerBase.cpp:563
bool enable_profiling
indicator that profiling is enabled
Definition BrokerBase.hpp:153
Time networkTimeout
timeout to establish a socket connection before giving up
Definition BrokerBase.hpp:67
std::atomic< int32_t > maxLogLevel
Definition BrokerBase.hpp:48
virtual void processCommand(ActionMessage &&cmd)=0
bool errorOnUnmatchedConnections
error if there are unmatched connections on init
Definition BrokerBase.hpp:156
std::size_t currentMessageCounter() const
Definition BrokerBase.hpp:318
std::atomic< bool > haltOperations
flag indicating that no further message should be processed
Definition BrokerBase.hpp:83
std::shared_ptr< LogManager > mLogManager
object to handle the logging considerations
Definition BrokerBase.hpp:117
GlobalBrokerId getGlobalId() const
Definition BrokerBase.hpp:236
int32_t minChildCount
Definition BrokerBase.hpp:57
std::unique_ptr< BaseTimeCoordinator > timeCoord
object managing the time control
Definition BrokerBase.hpp:115
void loadInfoFromJson(const std::string &json, bool runArgParser=true)
Definition BrokerBase.cpp:399
virtual std::string generateLocalAddressString() const =0
void logFlush()
Definition BrokerBase.cpp:763
std::function< void(int, std::string_view, std::string_view)> getLoggingCallback() const
Definition BrokerBase.cpp:90
bool asyncTime
flag indicating the use of async time keeping
Definition BrokerBase.hpp:95
std::string address
network location of the broker
Definition BrokerBase.hpp:79
Time queryTimeout
Definition BrokerBase.hpp:68
int32_t minLocalFederateCount
Definition BrokerBase.hpp:59
bool disableDynamicSources
flag disabling dynamic data sources
Definition BrokerBase.hpp:99
bool terminate_on_error
flag indicating that the federation should halt on any error
Definition BrokerBase.hpp:87
bool restrictive_time_policy
flag indicating the broker should use a conservative time policy
Definition BrokerBase.hpp:85
Time maxCoSimDuration
the maximum lifetime (wall clock time) of the co-simulation
Definition BrokerBase.hpp:72
virtual std::shared_ptr< helicsCLI11App > generateCLI()
Definition BrokerBase.cpp:105
bool hasTimeDependency
Definition BrokerBase.hpp:143
bool noAutomaticID
the broker should not automatically generate an ID
Definition BrokerBase.hpp:142
bool allowRemoteControl
Definition BrokerBase.hpp:154
bool uuid_like
will be set to true if the name looks like a uuid
Definition BrokerBase.hpp:150
bool enteredExecutionMode
flag indicating that the broker has entered execution mode
Definition BrokerBase.hpp:145
virtual bool tryReconnect()=0
Definition BrokerBase.cpp:870
void addBaseInformation(nlohmann::json &base, bool hasParent) const
Definition BrokerBase.cpp:736
Time errorDelay
time to delay before terminating after error state
Definition BrokerBase.hpp:70
bool waitingForBrokerPingReply
flag indicating we are waiting for a ping reply
Definition BrokerBase.hpp:146
void setErrorState(int eCode, std::string_view estring)
Definition BrokerBase.cpp:620
std::string lastErrorString
storage for last error string
Definition BrokerBase.hpp:164
void writeProfilingData()
Definition BrokerBase.cpp:605
virtual double getSimulationTime() const
Definition BrokerBase.hpp:306
bool useJsonSerialization
Definition BrokerBase.hpp:152
void generateNewIdentifier()
Definition BrokerBase.cpp:590
int32_t minBrokerCount
Definition BrokerBase.hpp:53
std::pair< bool, std::vector< std::string_view > > processBaseCommands(ActionMessage &command)
Definition BrokerBase.cpp:663
virtual void processPriorityCommand(ActionMessage &&command)=0
bool getFlagValue(int32_t flag) const
Definition BrokerBase.cpp:650
gmlc::containers::BlockingPriorityQueue< ActionMessage > actionQueue
primary routing queue
Definition BrokerBase.hpp:116
bool hasFilters
flag indicating filters come through the broker
Definition BrokerBase.hpp:147
std::atomic< GlobalBrokerId > global_id
Definition BrokerBase.hpp:43
void loadInfoFromToml(const std::string &toml, bool runArgParser=true)
Definition BrokerBase.cpp:481
int parseArgs(int argc, char *argv[])
Definition BrokerBase.cpp:317
Time grantTimeout
timeout for triggering diagnostic action waiting for a time grant
Definition BrokerBase.hpp:71
void setLogLevel(int32_t level)
Definition BrokerBase.cpp:758
Time tickTimer
the length of each heartbeat tick
Definition BrokerBase.hpp:65
std::vector< std::string > requiredFederates
Definition BrokerBase.hpp:63
bool dynamicFederation
flag indicating that the broker supports dynamic federates
Definition BrokerBase.hpp:97
virtual void processDisconnect(bool skipUnregister=false)=0
int32_t maxIterationCount
the maximum number of iterative loops that are allowed
Definition BrokerBase.hpp:64
bool globalDisconnect
Definition BrokerBase.hpp:157
GlobalBrokerId global_broker_id_local
Definition BrokerBase.hpp:44
decltype(std::chrono::steady_clock::now()) errorTimeStart
time when the error condition started; related to the errorDelay
Definition BrokerBase.hpp:160
void addActionMessage(const ActionMessage &message)
Definition BrokerBase.cpp:777
bool globalTime
flag indicating that the broker should use a global time coordinator
Definition BrokerBase.hpp:93
Definition GlobalFederateId.hpp:30
Definition GlobalFederateId.hpp:75
Definition TimeoutMonitor.h:27
@ HELICS_LOG_LEVEL_NO_PRINT
Definition helics_enums.h:206
action_t
Definition ActionMessageDefintions.hpp:20
the main namespace for the helics co-simulation library User functions will be in the helics namespac...
Definition AsyncFedCallInfo.hpp:14
constexpr GlobalBrokerId parent_broker_id
Definition GlobalFederateId.hpp:67
const std::string & brokerStateName(BrokerBase::BrokerState state)
Definition BrokerBase.cpp:1191
TimeRepresentation< count_time< 9 > > Time
Definition helicsTime.hpp:27
STL namespace.