Sen API
Sen Libraries
Loading...
Searching...
No Matches
component_api.h
Go to the documentation of this file.
1// === component_api.h =================================================================================================
2// Sen Infrastructure
3// Released under the Apache License v2.0 (SPDX-License-Identifier Apache-2.0).
4// See the LICENSE.txt file for more information.
5// © Airbus SAS, Airbus Helicopters, and Airbus Defence and Space SAU/GmbH/SAS.
6// =====================================================================================================================
7
8#ifndef SEN_KERNEL_COMPONENT_API_H
9#define SEN_KERNEL_COMPONENT_API_H
10
11// sen
16#include "sen/core/base/span.h"
19#include "sen/core/meta/var.h"
22#include "sen/core/obj/object.h"
26
27// kernel
28#include "sen/kernel/kernel.h"
30#include "sen/kernel/tracer.h"
32
33// generated code
34#include "stl/sen/kernel/basic_types.stl.h"
35
36// spdlog
37#include <spdlog/logger.h>
38
39// std
40#include <atomic>
41#include <cstdint>
42#include <cstring>
43#include <filesystem>
44#include <functional>
45#include <memory>
46#include <optional>
47#include <string>
48#include <string_view>
49#include <utility>
50#include <vector>
51
52namespace sen::kernel
53{
54
57
60
62class RunApi;
63class KernelApi;
64
65namespace impl
66{
67
68class Runner;
69class KernelImpl;
70
71[[nodiscard]] FuncResult execLoop(Runner* runner, Duration cycleTime, std::function<void()>&& workFunction);
72
73void installTransportFactory(KernelImpl* kernel, TransportFactory&& factory, uint32_t transportVersion);
74
75void remoteProcessDetected(RunApi& api, const ProcessInfo& processInfo);
76
77void remoteProcessLost(RunApi& api, const ProcessInfo& processInfo);
78
79[[nodiscard]] std::shared_ptr<ObjectSource> getSource(Runner* runner, const BusAddress& address);
80
81[[nodiscard]] SessionsDiscoverer& getSessionsDiscoverer(Runner* runner);
82
83[[nodiscard]] const ProcessInfo* fetchOwnerInfo(const Object* object);
84
85[[nodiscard]] ::sen::impl::WorkQueue* getWorkQueue(Runner* runner);
86
87[[nodiscard]] std::shared_ptr<spdlog::logger> getOrCreateLogger(const std::string& loggerName);
88
89void applyToAllLoggers(std::function<void(std::shared_ptr<spdlog::logger>)>&& func);
90
91} // namespace impl
92
95{
96 std::string name;
97 uint32_t group = 0;
98 bool requiresRealTime = false;
99 std::optional<Duration> cycleTime;
100 std::size_t objectCount = 0;
101};
102
105{
106 RunMode runMode = RunMode::realTime;
108 std::vector<ComponentMonitoringInfo> components;
109};
110
113{
114public:
115 KernelApi(Kernel& kernel, impl::Runner* runner) noexcept;
116
117public:
119 [[nodiscard]] CustomTypeRegistry& getTypes() noexcept;
120
123 void requestKernelStop(int exitCode = 0);
124
126 [[nodiscard]] std::shared_ptr<ObjectSource> getSource(const BusAddress& address);
127
130 [[nodiscard]] std::shared_ptr<ObjectSource> getSource(const std::string& address);
131
133 [[nodiscard]] SessionsDiscoverer& getSessionsDiscoverer() noexcept;
134
137 [[nodiscard]] const ProcessInfo* fetchOwnerInfo(const Object* object) const noexcept;
138
140 [[nodiscard]] const std::string& getAppName() const noexcept;
141
143 [[nodiscard]] ::sen::impl::WorkQueue* getWorkQueue() const noexcept;
144
145 template <typename T, typename Bus>
146 [[nodiscard]] std::shared_ptr<Subscription<T>> selectAllFrom(const Bus& bus);
147
151 template <typename T, typename Bus>
152 [[nodiscard]] std::shared_ptr<Subscription<T>> selectAllFrom(
153 const Bus& bus,
154 typename sen::ObjectList<T>::Callback onAdded,
155 typename sen::ObjectList<T>::Callback onRemoved = nullptr);
156
161 template <typename T, typename Bus>
162 [[nodiscard]] std::shared_ptr<Subscription<T>> selectFrom(const Bus& bus,
163 const std::string& query,
164 typename sen::ObjectList<T>::Callback onAdded = nullptr,
165 typename sen::ObjectList<T>::Callback onRemoved = nullptr);
166
169 [[nodiscard]] std::filesystem::path getConfigFilePath() const noexcept { return kernel_.getConfigPath(); }
170
173 [[nodiscard]] static std::shared_ptr<spdlog::logger> getOrCreateLogger(const std::string& loggerName);
174
176 static void applyToAllLoggers(std::function<void(std::shared_ptr<spdlog::logger>)>&& func);
177
178private:
179 template <typename T>
180 [[nodiscard]] std::string buildQuery(const BusAddress& address) const;
181
182 template <typename T>
183 [[nodiscard]] std::string buildQuery(std::string_view bus) const;
184
185private:
186 Kernel& kernel_;
187 impl::Runner* runner_;
188};
189
192{
193public:
194 explicit ConfigGetter(const VarMap& config) noexcept;
195
196public:
198 [[nodiscard]] const VarMap& getConfig() const noexcept;
199
200private:
201 const VarMap& config_;
202};
203
206{
207public:
208 SEN_NOCOPY_NOMOVE(RegistrationApi)
209
210public:
211 RegistrationApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
212 ~RegistrationApi() noexcept = default;
213};
214
216class PreloadApi: public ConfigGetter, public KernelApi
217{
218 SEN_NOCOPY_NOMOVE(PreloadApi)
219
220public:
221 PreloadApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
222
223 ~PreloadApi() noexcept = default;
224
225public:
227 void installTransportFactory(TransportFactory&& factory, uint32_t transportVersion) const;
228
230 void installTracerFactory(TracerFactory&& factory) const;
231
232private:
233 Kernel& kernel_;
234};
235
237class LoadApi: public ConfigGetter, public KernelApi
238{
239 SEN_NOCOPY_NOMOVE(LoadApi)
240
241public:
242 LoadApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
243
244 ~LoadApi() noexcept = default;
245};
246
248class InitApi: public ConfigGetter, public KernelApi
249{
250 SEN_NOCOPY_NOMOVE(InitApi)
251
252public:
253 InitApi(Kernel& kernel, impl::Runner* runner, const VarMap& config) noexcept;
254
255 ~InitApi() noexcept = default;
256};
257
259class RunApi: public ConfigGetter, public KernelApi
260{
261public:
262 SEN_NOCOPY_NOMOVE(RunApi)
263
264public:
266 impl::KernelImpl& kernelImpl,
267 impl::Runner* runner,
268 std::atomic_bool& stopRequested,
269 const VarMap& config,
270 Guarded<TimeStamp>& timePoint) noexcept;
271
272 ~RunApi() noexcept = default;
273
274public:
276 [[nodiscard]] const std::atomic_bool& stopRequested() const noexcept;
277
282
284 void update();
285
290 void commit();
291
294 [[nodiscard]] FuncResult execLoop(Duration cycleTime,
295 std::function<void()>&& func = nullptr,
296 bool logOverruns = true);
297
299 [[nodiscard]] TimeStamp getStartTime() const noexcept;
300
302 [[nodiscard]] TimeStamp getTime() const noexcept;
303
305 [[nodiscard]] std::optional<Duration> getTargetCycleTime() const noexcept;
306
309
313 [[nodiscard]] Span<const ComponentInfo> getImportedPackages() const noexcept;
314
320 [[nodiscard]] Span<const ComponentInfo> getLoadedComponents() const noexcept;
321
324 [[nodiscard]] std::optional<uint32_t> getTransportProtocolVersion() const noexcept;
325
327 [[nodiscard]] Tracer& getTracer() const noexcept;
328
329private:
330 friend void impl::remoteProcessDetected(RunApi& api, const ProcessInfo& processInfo);
331
332 friend void impl::remoteProcessLost(RunApi& api, const ProcessInfo& processInfo);
333
334private:
335 impl::KernelImpl& kernelImpl_;
336 impl::Runner* runner_;
337 std::atomic_bool& stopRequested_;
338 Guarded<TimeStamp>& timePoint_;
339};
340
342class UnloadApi: public ConfigGetter, public KernelApi
343{
344 SEN_NOCOPY_NOMOVE(UnloadApi)
345
346public:
347 UnloadApi(Kernel& kernel, const VarMap& config, impl::Runner* runner) noexcept;
348 ~UnloadApi() noexcept = default;
349};
350
351//----------------------------------------------------------------------------------------------------------------------
352// Inline implementation
353//----------------------------------------------------------------------------------------------------------------------
354
355template <typename T, typename Bus>
356inline std::shared_ptr<Subscription<T>> KernelApi::selectAllFrom(const Bus& bus)
357{
358 auto sub = std::make_shared<Subscription<T>>();
359 sub->attachTo(getSource(bus), Interest::make(buildQuery<T>(bus), getTypes()), true);
360 return sub;
361}
362
363template <typename T, typename Bus>
364inline std::shared_ptr<Subscription<T>> KernelApi::selectAllFrom(const Bus& bus,
365 typename ObjectList<T>::Callback onAdded,
366 typename ObjectList<T>::Callback onRemoved)
367{
368 auto sub = std::make_shared<Subscription<T>>();
369 // Install callbacks before subscribing so they fire for objects already present.
370 if (onAdded)
371 {
372 std::ignore = sub->list.onAdded(std::move(onAdded));
373 }
374 if (onRemoved)
375 {
376 std::ignore = sub->list.onRemoved(std::move(onRemoved));
377 }
378 sub->attachTo(getSource(bus), Interest::make(buildQuery<T>(bus), getTypes()), true);
379 return sub;
380}
381
382template <typename T, typename Bus>
383inline std::shared_ptr<Subscription<T>> KernelApi::selectFrom(const Bus& bus,
384 const std::string& query,
385 typename sen::ObjectList<T>::Callback onAdded,
386 typename sen::ObjectList<T>::Callback onRemoved)
387{
388 auto sub = std::make_shared<Subscription<T>>();
389
390 // Install callbacks before subscribing so they fire for objects already present.
391 if (onAdded)
392 {
393 std::ignore = sub->list.onAdded(std::move(onAdded));
394 }
395 if (onRemoved)
396 {
397 std::ignore = sub->list.onRemoved(std::move(onRemoved));
398 }
399 sub->attachTo(getSource(bus), Interest::make(query, getTypes()), true);
400 return sub;
401}
402
403template <typename T>
404inline std::string KernelApi::buildQuery(const BusAddress& address) const
405{
406 const ClassType* meta = nullptr;
407 if constexpr (!std::is_same_v<T, Object>)
408 {
409 meta = &T::meta();
410 }
411
412 std::string query = "SELECT ";
413 query.append(meta ? meta->getQualifiedName() : "*");
414 query.append(" FROM ");
415 query.append(address.sessionName);
416 query.append(".");
417 query.append(address.busName);
418
419 return query;
420}
421
422template <typename T>
423inline std::string KernelApi::buildQuery(std::string_view bus) const
424{
425 const ClassType* meta = nullptr;
426 if constexpr (!std::is_same_v<T, Object>)
427 {
428 meta = T::meta()->asClassType();
429 }
430
431 std::string query = "SELECT ";
432 query.append(meta ? meta->getQualifiedName() : "*");
433 query.append(" FROM ");
434 query.append(bus);
435
436 return query;
437}
438
439} // namespace sen::kernel
440
441#endif // SEN_KERNEL_COMPONENT_API_H
Base class for event or method callbacks. It stores the queue where to push the response....
Definition callback.h:146
A registry of custom types.
Definition type_registry.h:36
A time duration.
Definition duration.h:25
static std::shared_ptr< Interest > make(std::string_view query, const CustomTypeRegistry &typeRegistry)
Make an interest from a query. Throws std::exception if not well formed.
A sen object.
Definition object.h:76
A list of objects that is managed by some source based on user-expressed interests.
Definition object_list.h:30
std::function< void(const Iterators &iterators)> Callback
Definition object_list.h:65
Allows adding and receiving objects.
Definition object_source.h:35
Result<T, E> is a template type that can be used to return and propagate errors. The intent is to rep...
Definition result.h:135
Contiguous view of elements of type T. Inspired by http://www.open-std.org/jtc1/sc22/wg21/docs/papers...
Definition span.h:34
A point in time.
Definition timestamp.h:26
ConfigGetter(const VarMap &config) noexcept
const VarMap & getConfig() const noexcept
Gets the configuration associated with this component.
~InitApi() noexcept=default
InitApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
User-facing kernel functions.
Definition component_api.h:113
::sen::impl::WorkQueue * getWorkQueue() const noexcept
The work queue of this runner.
KernelApi(Kernel &kernel, impl::Runner *runner) noexcept
std::shared_ptr< Subscription< T > > selectFrom(const Bus &bus, const std::string &query, typename sen::ObjectList< T >::Callback onAdded=nullptr, typename sen::ObjectList< T >::Callback onRemoved=nullptr)
Creates a subscription for objects matching the given Sen query string. Unlike selectAllFrom,...
Definition component_api.h:383
std::shared_ptr< ObjectSource > getSource(const BusAddress &address)
Gets an object source, where objects can be found and published.
std::filesystem::path getConfigFilePath() const noexcept
Gets the path to the configuration file used to construct the kernel. It might be empty if the kernel...
Definition component_api.h:169
CustomTypeRegistry & getTypes() noexcept
The types registered into the kernel.
static std::shared_ptr< spdlog::logger > getOrCreateLogger(const std::string &loggerName)
Registers a new logger in the kernel if it does not exist, or returns the existing one by name....
SessionsDiscoverer & getSessionsDiscoverer() noexcept
Object that allows discovering sessions and buses.
const ProcessInfo * fetchOwnerInfo(const Object *object) const noexcept
Gets information about the process where an object is. Returns nullptr if the object resides in the c...
const std::string & getAppName() const noexcept
Gets the (optional) application name passed to the kernel as a configuration parameter.
static void applyToAllLoggers(std::function< void(std::shared_ptr< spdlog::logger >)> &&func)
Applies the input function to all loggers kept in the logger registry. Used by the logmaster componen...
void requestKernelStop(int exitCode=0)
Issues an asynchronous request to stop the kernel. The request is ignored if a previous stop request ...
std::shared_ptr< Subscription< T > > selectAllFrom(const Bus &bus)
Definition component_api.h:356
Main entry point of a sen microkernel.
Definition kernel.h:40
~LoadApi() noexcept=default
LoadApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
PreloadApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
~PreloadApi() noexcept=default
void installTracerFactory(TracerFactory &&factory) const
Installs a tracer factory.
void installTransportFactory(TransportFactory &&factory, uint32_t transportVersion) const
Installs a transport factory for the kernel to use for sessions.
RegistrationApi(Kernel &kernel, impl::Runner *runner, const VarMap &config) noexcept
~RegistrationApi() noexcept=default
What can be done while a component is running.
Definition component_api.h:260
Span< const ComponentInfo > getLoadedComponents() const noexcept
Build information for every component loaded into the kernel, excluding pipeline components (which ar...
TimeStamp getStartTime() const noexcept
The initial simulation time for the objects in the component.
Span< const ComponentInfo > getImportedPackages() const noexcept
Build information for all imported packages (from pipeline components). The returned span references ...
void commit()
Send changes, so that they become visible to other participants. This includes object additions and r...
Tracer & getTracer() const noexcept
Create a scoped zone used for tracing runtime performance.
void drainInputs()
Perform any request coming from the outside and drainInputs all the local data structures with their ...
~RunApi() noexcept=default
std::optional< Duration > getTargetCycleTime() const noexcept
If present, it returns the configured cycle time for iterations.
std::optional< uint32_t > getTransportProtocolVersion() const noexcept
Version of the currently installed transport protocol. Empty when no transport is installed....
FuncResult execLoop(Duration cycleTime, std::function< void()> &&func=nullptr, bool logOverruns=true)
A basic execution loop. Func is an optional callback that will be invoked on each cycle.
RunApi(Kernel &kernel, impl::KernelImpl &kernelImpl, impl::Runner *runner, std::atomic_bool &stopRequested, const VarMap &config, Guarded< TimeStamp > &timePoint) noexcept
KernelMonitoringInfo fetchMonitoringInfo() const
Monitoring information.
friend void impl::remoteProcessLost(RunApi &api, const ProcessInfo &processInfo)
const std::atomic_bool & stopRequested() const noexcept
True if stop has been requested by the runtime.
void update()
This calls update() on all the objects registered by the component.
friend void impl::remoteProcessDetected(RunApi &api, const ProcessInfo &processInfo)
TimeStamp getTime() const noexcept
The (potentially virtualized) time.
Definition source_info.h:99
Interface implemented by tracers. You can use it to trace the behavior of your code....
Definition tracer.h:28
UnloadApi(Kernel &kernel, const VarMap &config, impl::Runner *runner) noexcept
~UnloadApi() noexcept=default
std::function< std::unique_ptr< Transport >(const std::string &, std::unique_ptr< Tracer > tracer)> TransportFactory
A function that creates a transport given a session name.
Definition include/sen/kernel/transport.h:203
Global transport statistics.
Definition include/sen/kernel/transport.h:146
std::map< std::string, Var, std::less<> > VarMap
A map of vars to represent structures.
Definition var.h:107
Strong type for the unique identifier for a transport timer.
Definition native_object_impl.h:39
uint32_t group
Definition component_api.h:97
Result< OpState, ExecError > PassResult
The result of operations that may be called multiple times.
Definition component_api.h:59
std::function< std::unique_ptr< Tracer >(std::string_view)> TracerFactory
A factory function for tracers.
Definition tracer.h:119
Result< void, ExecError > FuncResult
The result of operations that are called once.
Definition component_api.h:56
std::optional< Duration > cycleTime
Definition component_api.h:99
std::vector< ComponentMonitoringInfo > components
Definition component_api.h:108
std::size_t objectCount
Definition component_api.h:100
std::string name
Definition component_api.h:96
RunMode runMode
Definition component_api.h:106
bool requiresRealTime
Definition component_api.h:98
TransportStats transportStats
Definition component_api.h:107
Runtime monitoring information about a single component runner.
Definition component_api.h:95
Kernel runtime monitoring information.
Definition component_api.h:105
Definition assert.h:17
STL namespace.
Guarded is a lightweight wrapper class that can be used to protect an objet of type T from concurrent...
Definition mutex_utils.h:49
A list of objects and a reference to its source (to keep it alive).
Definition subscription.h:29