srs-control 0.2.2
Loading...
Searching...
No Matches
Application.cpp
Go to the documentation of this file.
1#include "srs/Application.hpp"
12
13#include "spdlog/sinks/rotating_file_sink.h"
14#include <algorithm>
15#include <asio/error.hpp>
16#include <asio/executor_work_guard.hpp>
17#include <asio/strand.hpp>
18#include <chrono>
19#include <cstddef>
20#include <exception>
21#include <expected>
22#include <fmt/base.h>
23#include <fmt/color.h>
24#include <fmt/format.h>
25#include <fmt/ranges.h>
26#include <format>
27#include <future>
28#include <initializer_list>
29#include <memory>
30#include <print>
31#include <source_location>
32#include <spdlog/common.h>
33#include <spdlog/logger.h>
34#include <spdlog/sinks/stdout_color_sinks.h>
35#include <spdlog/spdlog.h>
36#include <stdexcept>
37#include <string>
38#include <string_view>
39#include <system_error>
40#include <thread>
41#include <utility>
42#include <vector>
43
44namespace srs
45{
46 internal::AppExitHelper::~AppExitHelper() noexcept { app_->action_after_destructor(); }
47
49 {
50 auto log_file = common::get_default_log_path();
51
52 auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
53 if (config_.show_thread_id)
54 {
55 console_sink->set_pattern("[%H:%M:%S][%^%=6l%$][%t] %v");
56 }
57 else
58 {
59 console_sink->set_pattern("[%H:%M:%S][%^%=6l%$] %v");
60 }
61 auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
62 log_file.string(), common::file_max_size, common::rotating_file_nums, false);
63 file_sink->set_level(spdlog::level::trace);
64 file_sink->set_pattern("[%Y-%m-%d %H:%M:%S][%l][%t] %v");
65
66 auto logger =
67 std::make_shared<spdlog::logger>("multi_sink", spdlog::sinks_init_list{ console_sink, file_sink });
68 logger->set_level(spdlog::level::trace);
69
70 console_sink->set_level(spdlog::level::off);
71 logger->info("");
72 logger->info("{}", common::file_logger_new_instance_str);
73 logger->info("");
74 console_sink->set_level(spdlog::level::trace);
75
76 spdlog::register_logger(logger);
77 spdlog::set_default_logger(logger);
78
79 // spdlog::set_pattern("[%H:%M:%S][%^%=6l%$][%t] %v");
80 spdlog::info("Welcome to SRS Application");
81 }
82
84 : config_{ std::move(config) }
85 , report_{ std::make_unique<AppReport>() }
86 , io_work_guard_{ asio::make_work_guard(io_context_) }
87 , fec_strand_{ asio::make_strand(io_context_.get_executor()) }
88 {
90 }
91
93 {
94 auto _ = ExitLogger{};
95 io_work_guard_.reset();
96 if (auto switch_off_status = wait_for_switch_action(switch_off_future_);
97 switch_off_status == std::future_status::ready)
98 {
99 spdlog::info(fmt::format(fg(fmt::color::light_green) | fmt::emphasis::bold,
100 "🥳 FECs have been switched off successfully!"));
101 }
102 else if (switch_off_status == std::future_status::timeout)
103 {
104 spdlog::warn("Application: TIMEOUT while waiting for switching off process to finish.");
105 }
106 else if (switch_off_status == std::future_status::deferred)
107 {
108 spdlog::warn("Application: Switching off of FECs is pending.");
109 }
110 else if (not switch_off_status.has_value())
111 {
112 spdlog::debug("Application: FECs don't need switching off due to: {}", switch_off_status.error().message());
113 }
114
115 // TODO: set a timer
116 //
117 if (working_thread_.joinable())
118 {
119 spdlog::debug("Application: Wait until working thread finishes ...");
120 working_thread_.join();
121 spdlog::debug("Application: All tasks in main io_context are finished.");
122 }
123 }
124
125 App::~App() noexcept
126 {
127 auto _ = ExitLogger{};
128
130 }
131
133 {
134 if (workflow_handler_ != nullptr)
135 {
136 workflow_handler_->print_statistics();
137 }
138 }
139
141 {
142 if (runtime_sec_ == 0)
143 {
144 spdlog::info(
145 fmt::format(fmt::emphasis::bold,
146 "📢 Application is running in non-stop mode. Press \"Ctrl-C\" to stop the application!"));
147 signal_set_.async_wait(
148 [this](const std::error_code& error, auto)
149 {
150 const auto _ = ExitLogger{ "signal" };
151 std::println("\n");
152 spdlog::info("Calling SIGINT from the user input");
153 if (error == asio::error::operation_aborted)
154 {
155 return;
156 }
158 });
159 }
160 else
161 {
162 spdlog::info(fmt::format(fmt::emphasis::bold,
163 "📢 Application is running in stop mode and will stop after {} seconds!",
164 runtime_sec_));
165 cancel_timer_.expires_after(std::chrono::seconds{ runtime_sec_ });
166 cancel_timer_.async_wait(
167 [this](const std::error_code&)
168 {
169 std::println("\n");
171 });
172 }
173 }
174
176 {
177 const auto _ = ExitLogger{};
178 workflow_handler_ = std::make_unique<workflow::AnalysisHandle>(this, config_.output_split);
179 workflow_handler_->set_print_mode(config_.data_print_mode);
180 workflow_handler_->set_output_filenames(config_.output_filenames);
181
184
186
187 auto current_loc = std::source_location::current();
188 auto monitoring_action = [this, current_loc]()
189 {
190 try
191 {
192 auto _ = ExitLogger{ "io_context join", current_loc };
193 io_context_.join();
194 }
195 catch (const std::exception& ex)
196 {
197 spdlog::critical("Application: Exception on working thread occurred: {}", ex.what());
198 }
199 };
200 working_thread_ = std::jthread{ monitoring_action };
201 }
202
204 {
205 const auto _ = ExitLogger{};
206 // sequentially waiting
207 for (auto& socket : data_sockets_)
208 {
209 if (socket == nullptr)
210 {
211 continue;
212 }
213 socket->cancel();
214 auto status = socket->wait_for_listen_finish(common::DEFAULT_STATUS_WAITING_TIME_SECONDS);
215 if (status.has_value() and status.value() == std::future_status::timeout)
216 {
217 spdlog::warn("Application: TIMEOUT during waiting for the closing of input data stream.");
218 }
219 }
220 }
221
222 // This will be called by Ctrl-C interrupt
224 {
225 spdlog::debug("Application: exiting ...");
226 auto _ = ExitLogger{};
227 spdlog::default_logger()->flush();
228 spdlog::flush_every(std::chrono::seconds{ 1 });
229
230 auto err = std::error_code{};
231 signal_set_.cancel(err);
232 signal_set_.clear(err);
233
234 workflow_handler_->stop_monitor();
235
236 if (auto switch_on_status = wait_for_switch_action(switch_on_future_);
237 switch_on_status == std::future_status::ready)
238 {
239 spdlog::debug("Application: FECs have been switched on successfully.");
240 switch_off();
241 }
242 else if (switch_on_status == std::future_status::timeout)
243 {
244 spdlog::warn(
245 "Application: TIMEOUT during waiting for FECs to be switched on. Skipping switching off process.");
246 }
247 else if (switch_on_status == std::future_status::deferred)
248 {
249 spdlog::warn("Application: Switching on of FECs is pending. Skipping switching off process.");
250 }
251 else
252 {
253 spdlog::info("FECs were not switched on. Skipping switching off process.");
254 }
255
256 std::this_thread::sleep_for(std::chrono::milliseconds{ config_.time_wait_after_acq_off_ms });
257
258 // Turn off SRS data acquisition
260
261 workflow_handler_->stop_workflow();
262 }
263
264 void App::set_print_mode(common::DataPrintMode mode) { config_.data_print_mode = mode; }
265 void App::set_output_filenames(const std::vector<std::string>& filenames, std::size_t n_lines)
266 {
267 config_.output_filenames = filenames;
268 config_.output_split = n_lines;
269 }
270
271 void App::add_remote_fec_endpoint(std::string_view remote_ip, int port_number)
272 {
273 auto resolver = udp::resolver{ io_context_ };
274 spdlog::info("Add the remote FEC with ip: {} and port: {}", remote_ip, port_number);
275 auto udp_endpoints = resolver.resolve(udp::v4(), remote_ip, fmt::format("{}", port_number));
276
277 if (udp_endpoints.begin() == udp_endpoints.end())
278 {
279 spdlog::debug("Application: Failed to add the FEC remote point");
280 return;
281 }
282 remote_fec_endpoints_.push_back(*udp_endpoints.begin());
283 }
284
285 template <typename T>
286 auto App::switch_FECs(std::string_view connection_name) -> SwitchFutureType
287 {
290 .transform(
291 [this, connection_name](const std::shared_ptr<connection::FecCommandSocket>& socket)
292 {
293 socket->set_report(report_.get());
294 for (const auto& remote_endpoint : remote_fec_endpoints_)
295 {
296 spdlog::info("Switching {} FEC device with remote endpoint {} ...", T::tag, remote_endpoint);
297 auto fec_connection = std::make_shared<T>(connection_name);
298 fec_connection->set_remote_endpoint(remote_endpoint);
299 fec_connection->send_message_from(socket);
300 }
301 auto res_fut = socket->cancel_listen_after(io_context_);
302 socket->launch_send_actions();
303 return res_fut;
304 });
305 }
306
308
310 {
311 spdlog::info(fmt::format(fmt::emphasis::bold, "❗ Please wait until FEC devices are switched off"));
313 }
314
316 {
317 const auto& data_ports = config_.fec_data_receive_ports;
318
319 if (auto port = std::ranges::find(data_ports, config_.fec_control_local_port); port != data_ports.end())
320 {
321 throw std::runtime_error(
322 std::format("Application: port number {} used for input data stream is not allowed to be the same "
323 "port number used for the local control port {}.",
324 *port,
325 config_.fec_control_local_port));
326 }
327 return true;
328 }
329
330 void App::read_data(bool /*is_non_stop*/)
331 {
332 spdlog::info("Starting input data stream from local port number(s): [{}]...",
333 fmt::join(config_.fec_data_receive_ports, ", "));
334 for (const auto port_num : config_.fec_data_receive_ports)
335 {
336 auto status =
338 port_num, io_context_, config_.data_buffer_size, *workflow_handler_)
339 .transform(
340 [this](auto socket)
341 {
342 socket->set_report(report_.get());
343 spdlog::debug("data stream is using the buffer size: {}", config_.data_buffer_size);
344 data_sockets_.push_back(std::move(socket));
345 });
346
347 if (not status.has_value())
348 {
349 spdlog::critical("Application: Cannot establish the connection for the input data stream because the "
350 "local port number "
351 "{} is not available.",
352 port_num);
353 }
354 }
355 }
356
358 {
359 workflow_thread_ = std::jthread(
360 [this]()
361 {
362 spdlog::info("Starting input data analysis workflow ...");
363 workflow_handler_->start(io_context_.get_executor());
364 });
365 }
366
368 {
369 if (not switch_future->valid())
370 {
371 return std::unexpected{ asio::error::make_error_code(asio::error::basic_errors::invalid_argument) };
372 }
373 return switch_future.transform(
374 [](const std::future<void>& switch_fut)
375 {
376 if (switch_fut.valid())
377 {
378 return switch_fut.wait_for(common::DEFAULT_STATUS_WAITING_TIME_SECONDS);
379 };
380 return std::future_status::ready;
381 });
382 }
383
385 {
386 for (const auto& fec_ips : config_.remote_fec_ips)
387 {
389 }
390 }
391} // namespace srs
~App() noexcept
Destructor of the App class.
asio::executor_work_guard< io_context_type::executor_type > io_work_guard_
Asio io_context work guard.
void init()
Initialization of internal members.
SwitchFutureType switch_on_future_
void read_data(bool is_non_stop=true)
Start reading the input data stream from the port specified by srs::Config::fec_data_receive_port....
void set_output_filenames(const std::vector< std::string > &filenames, std::size_t n_lines=1)
Set the output filenames.
void add_remote_fec_endpoint(std::string_view remote_ip, int port_number)
asio::signal_set signal_set_
User signal handler for interrupts.
std::vector< udp::endpoint > remote_fec_endpoints_
Remote endpoints of FEC devices.
void exit_and_switch_off()
void start_workflow()
Start data analysis workflow, triggering data conversions.
std::jthread working_thread_
Main working thread.
void set_print_mode(common::DataPrintMode mode)
Set the print mode.
void switch_off()
Establish the communications to the available FECs to stop the data acquisition.
asio::steady_timer cancel_timer_
Cancelling timer.
void set_cancel_method()
std::vector< std::shared_ptr< connection::DataSocket > > data_sockets_
Communication to the main input data stream.
void init_spdlog()
std::unique_ptr< AppReport > report_
std::unique_ptr< workflow::AnalysisHandle > workflow_handler_
The handler to the analysis working flow.
asio::strand< io_context_type::executor_type > fec_strand_
FEC communication strand for synchronous communications.
auto check_port_number_validity() -> bool
void set_remote_fec_endpoints()
static auto wait_for_switch_action(const SwitchFutureType &switch_future) -> SwitchFutureStatusType
SwitchFutureType switch_off_future_
Config config_
io_context_type io_context_
Asio io_context that manages the task scheduling and network IO.
void print_statistics() const
std::jthread workflow_thread_
Main thread to run workflow.
void switch_on()
Establish the communications to the available FECs to start the data acquisition.
App(Config config)
Constructor of the App class.
std::size_t runtime_sec_
Time duration (seconds) to stop the application. If value is zero, the application is in non-stop mod...
auto switch_FECs(std::string_view connection_name) -> SwitchFutureType
std::expected< std::future< void >, std::error_code > SwitchFutureType
void wait_for_reading_finish()
std::expected< std::future_status, std::error_code > SwitchFutureStatusType
void action_after_destructor()
static auto create(int port_number, io_context_type &io_context, Args &&... args) -> std::expected< std::shared_ptr< SocketType >, std::error_code >
~AppExitHelper() noexcept
Destructor calling srs::App::end_of_work method.
constexpr auto file_logger_new_instance_str
constexpr auto rotating_file_nums
constexpr auto file_max_size
file size limited to 10 MB.
constexpr auto DEFAULT_STATUS_WAITING_TIME_SECONDS
DataPrintMode
Print mode of the status line.
auto get_default_log_path() -> std::filesystem::path
constexpr auto DEFAULT_SRS_CONTROL_PORT
Main configuration struct.